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 == PeriodFreq::Business {
11186 let start = self.start_nanos()?;
11189 let end = start.checked_add(Timedelta::NANOS_PER_DAY - 1)?;
11190 return (end != Timestamp::NAT).then_some(end);
11191 }
11192 let next = Self::new(self.ordinal.checked_add(self.freq.multiplier())?, self.freq);
11193 let end = next.start_nanos()?.checked_sub(1)?;
11194 (end != Timestamp::NAT).then_some(end)
11195 }
11196
11197 #[must_use]
11200 pub fn start_time(&self) -> Timestamp {
11201 self.start_nanos()
11202 .map_or_else(Timestamp::nat, Timestamp::from_nanos)
11203 }
11204
11205 #[must_use]
11208 pub fn end_time(&self) -> Timestamp {
11209 self.end_nanos()
11210 .map_or_else(Timestamp::nat, Timestamp::from_nanos)
11211 }
11212
11213 pub fn to_timestamp(&self, how: &str) -> Result<Timestamp, TypeError> {
11216 match how.trim().to_ascii_lowercase().as_str() {
11217 "" | "s" | "start" | "begin" | "b" => Ok(self.start_time()),
11218 "e" | "end" | "finish" => Ok(self.end_time()),
11219 _ => Err(TypeError::ValueNotParseable {
11220 value: how.to_owned(),
11221 target: "Period::to_timestamp how ('start' or 'end')".to_owned(),
11222 }),
11223 }
11224 }
11225
11226 pub fn asfreq(&self, freq: &str) -> Result<Self, TypeError> {
11229 self.asfreq_with_how(freq, "end")
11230 }
11231
11232 pub fn asfreq_with_how(&self, freq: &str, how: &str) -> Result<Self, TypeError> {
11235 let target_freq = PeriodFreq::parse(freq).ok_or_else(|| TypeError::ValueNotParseable {
11236 value: freq.to_owned(),
11237 target: "PeriodFreq".to_owned(),
11238 })?;
11239 let is_start = match how.trim().to_ascii_lowercase().as_str() {
11240 "" | "e" | "end" | "finish" => false,
11241 "s" | "start" | "begin" | "b" => true,
11242 _ => {
11243 return Err(TypeError::ValueNotParseable {
11244 value: how.to_owned(),
11245 target: "Period::asfreq how ('start' or 'end')".to_owned(),
11246 });
11247 }
11248 };
11249 if self.is_nat() {
11250 return Ok(Self::new(i64::MIN, target_freq));
11251 }
11252 let boundary_nanos = if is_start {
11253 self.start_nanos()
11254 } else if self.freq.base() == PeriodFreq::Business && self.freq != PeriodFreq::Business {
11255 self.ordinal
11256 .checked_add(self.freq.multiplier() - 1)
11257 .and_then(|last| Self::new(last, PeriodFreq::Business).end_nanos())
11258 } else {
11259 self.end_nanos()
11260 }
11261 .ok_or_else(|| TypeError::ValueNotParseable {
11262 value: self.to_string(),
11263 target: "Period boundary Timestamp".to_owned(),
11264 })?;
11265 let flips = target_freq.base() == PeriodFreq::Business
11269 && Self::fixed_span_nanos(self.freq).is_some();
11270 let roll_business_forward = if flips { !is_start } else { is_start };
11271 Self::from_timestamp_nanos_with_business_roll(
11272 boundary_nanos,
11273 target_freq,
11274 roll_business_forward,
11275 )
11276 .ok_or_else(|| TypeError::ValueNotParseable {
11277 value: self.to_string(),
11278 target: format!("Period[{target_freq}]"),
11279 })
11280 }
11281
11282 fn field_timestamp(&self) -> Timestamp {
11287 if self.is_nat() {
11288 return Timestamp::nat();
11289 }
11290 let base = Self::new(self.ordinal, self.freq.base());
11294 let nanos = match base.freq {
11295 PeriodFreq::Daily
11296 | PeriodFreq::Business
11297 | PeriodFreq::Hourly
11298 | PeriodFreq::Minutely
11299 | PeriodFreq::Secondly
11300 | PeriodFreq::Milliseconds
11301 | PeriodFreq::Microseconds
11302 | PeriodFreq::Nanoseconds => base.start_nanos(),
11303 PeriodFreq::Weekly(_)
11304 | PeriodFreq::Monthly
11305 | PeriodFreq::Quarterly(_)
11306 | PeriodFreq::Annual(_) => base
11307 .end_nanos()
11308 .map(|end| end - end.rem_euclid(Timedelta::NANOS_PER_DAY)),
11309 PeriodFreq::Multiple(_) => None,
11310 };
11311 nanos.map_or_else(Timestamp::nat, Timestamp::from_nanos)
11312 }
11313
11314 #[must_use]
11317 pub fn strftime(&self, fmt: &str) -> String {
11318 self.field_timestamp().strftime(fmt)
11319 }
11320
11321 #[must_use]
11323 pub fn year(&self) -> Option<i64> {
11324 self.field_timestamp().year()
11325 }
11326
11327 #[must_use]
11329 pub fn month(&self) -> Option<i64> {
11330 self.field_timestamp().month()
11331 }
11332
11333 #[must_use]
11335 pub fn day(&self) -> Option<i64> {
11336 self.field_timestamp().day()
11337 }
11338
11339 #[must_use]
11341 pub fn hour(&self) -> Option<i64> {
11342 self.field_timestamp().hour()
11343 }
11344
11345 #[must_use]
11347 pub fn minute(&self) -> Option<i64> {
11348 self.field_timestamp().minute()
11349 }
11350
11351 #[must_use]
11353 pub fn second(&self) -> Option<i64> {
11354 self.field_timestamp().second()
11355 }
11356
11357 #[must_use]
11360 pub fn quarter(&self) -> Option<i64> {
11361 if self.is_nat() {
11362 return None;
11363 }
11364 match self.freq.base() {
11365 PeriodFreq::Quarterly(_) => Some(self.ordinal.rem_euclid(4) + 1),
11366 _ => self.field_timestamp().quarter(),
11367 }
11368 }
11369
11370 #[must_use]
11372 pub fn qyear(&self) -> Option<i64> {
11373 if self.is_nat() {
11374 return None;
11375 }
11376 match self.freq.base() {
11377 PeriodFreq::Quarterly(_) => 1970_i64.checked_add(self.ordinal.div_euclid(4)),
11378 _ => self.year(),
11379 }
11380 }
11381
11382 #[must_use]
11384 pub fn dayofweek(&self) -> Option<i64> {
11385 self.field_timestamp().dayofweek()
11386 }
11387
11388 #[must_use]
11390 pub fn day_of_week(&self) -> Option<i64> {
11391 self.dayofweek()
11392 }
11393
11394 #[must_use]
11396 pub fn weekday(&self) -> Option<i64> {
11397 self.dayofweek()
11398 }
11399
11400 #[must_use]
11402 pub fn dayofyear(&self) -> Option<i64> {
11403 self.field_timestamp().dayofyear()
11404 }
11405
11406 #[must_use]
11408 pub fn day_of_year(&self) -> Option<i64> {
11409 self.dayofyear()
11410 }
11411
11412 #[must_use]
11414 pub fn days_in_month(&self) -> Option<i64> {
11415 self.field_timestamp().days_in_month()
11416 }
11417
11418 #[must_use]
11420 pub fn daysinmonth(&self) -> Option<i64> {
11421 self.days_in_month()
11422 }
11423
11424 #[must_use]
11426 pub fn week(&self) -> Option<i64> {
11427 self.field_timestamp().week()
11428 }
11429
11430 #[must_use]
11432 pub fn weekofyear(&self) -> Option<i64> {
11433 self.week()
11434 }
11435
11436 #[must_use]
11438 pub fn is_leap_year(&self) -> Option<bool> {
11439 self.field_timestamp().is_leap_year()
11440 }
11441
11442 pub fn parse(s: &str) -> Result<Self, TypeError> {
11449 let trimmed = s.trim();
11450 if trimmed.eq_ignore_ascii_case("nat") {
11451 return Ok(Self::new(i64::MIN, PeriodFreq::Daily));
11452 }
11453
11454 if let Some((year, quarter)) = parse_quarter_period(trimmed) {
11455 let ordinal = year
11456 .checked_sub(1970)
11457 .and_then(|offset| offset.checked_mul(4))
11458 .and_then(|base| base.checked_add(i64::from(quarter) - 1))
11459 .ok_or_else(|| TypeError::ValueNotParseable {
11460 value: s.to_owned(),
11461 target: "Period".to_owned(),
11462 })?;
11463 return Ok(Self::new(ordinal, PeriodFreq::QUARTERLY));
11464 }
11465
11466 if let Some((year, month, day)) = parse_ymd_period(trimmed) {
11467 let ordinal = Timestamp::days_from_ymd(year, i64::from(month), i64::from(day));
11468 return Ok(Self::new(ordinal, PeriodFreq::Daily));
11469 }
11470
11471 if let Some((year, month)) = parse_year_month_period(trimmed) {
11472 let ordinal = year
11473 .checked_sub(1970)
11474 .and_then(|offset| offset.checked_mul(12))
11475 .and_then(|base| base.checked_add(i64::from(month) - 1))
11476 .ok_or_else(|| TypeError::ValueNotParseable {
11477 value: s.to_owned(),
11478 target: "Period".to_owned(),
11479 })?;
11480 return Ok(Self::new(ordinal, PeriodFreq::Monthly));
11481 }
11482
11483 if let Some(year) = parse_annual_period(trimmed) {
11484 let ordinal = year
11485 .checked_sub(1970)
11486 .ok_or_else(|| TypeError::ValueNotParseable {
11487 value: s.to_owned(),
11488 target: "Period".to_owned(),
11489 })?;
11490 return Ok(Self::new(ordinal, PeriodFreq::ANNUAL));
11491 }
11492
11493 Err(TypeError::ValueNotParseable {
11494 value: s.to_owned(),
11495 target: "Period".to_owned(),
11496 })
11497 }
11498
11499 #[must_use]
11524 pub fn calendar_string(&self) -> String {
11525 let mut rendered = String::new();
11526 let _ = self.write_calendar(&mut rendered);
11528 rendered
11529 }
11530
11531 fn write_calendar(&self, rendered: &mut impl std::fmt::Write) -> std::fmt::Result {
11532 if self.ordinal == i64::MIN {
11533 return rendered.write_str("NaT");
11534 }
11535 let ord = self.ordinal;
11536 match self.freq.base() {
11537 PeriodFreq::Annual(_) => {
11541 let year = 1970 + ord;
11542 write!(rendered, "{year}")
11543 }
11544 PeriodFreq::Quarterly(_) => {
11545 let year = 1970 + ord.div_euclid(4);
11546 let quarter = ord.rem_euclid(4) + 1;
11547 write!(rendered, "{year}Q{quarter}")
11548 }
11549 PeriodFreq::Monthly => {
11550 let year = 1970 + ord.div_euclid(12);
11551 let month = ord.rem_euclid(12) + 1;
11552 write!(rendered, "{year:04}-{month:02}")
11553 }
11554 PeriodFreq::Daily => {
11555 let (y, m, d) = civil_from_days(ord);
11556 write!(rendered, "{y:04}-{m:02}-{d:02}")
11557 }
11558 PeriodFreq::Business => {
11569 const WEEKDAY_OFFSET: [i64; 5] = [0, 1, 4, 5, 6];
11570 let offset = WEEKDAY_OFFSET[ord.rem_euclid(5) as usize];
11573 let days = ord.div_euclid(5).saturating_mul(7).saturating_add(offset);
11574 let (y, m, d) = civil_from_days(days);
11575 write!(rendered, "{y:04}-{m:02}-{d:02}")
11576 }
11577 PeriodFreq::Weekly(_) => {
11587 const WEEK_ANCHOR_DAY: i64 = -10;
11591 let start = ord
11592 .saturating_mul(7)
11593 .saturating_add(WEEK_ANCHOR_DAY + self.freq.week_start_shift());
11594 let (sy, sm, sd) = civil_from_days(start);
11595 let (ey, em, ed) = civil_from_days(start.saturating_add(6));
11596 write!(rendered, "{sy:04}-{sm:02}-{sd:02}/{ey:04}-{em:02}-{ed:02}")
11597 }
11598 PeriodFreq::Hourly => {
11599 let (y, m, d) = civil_from_days(ord.div_euclid(24));
11600 let hour = ord.rem_euclid(24);
11601 write!(rendered, "{y:04}-{m:02}-{d:02} {hour:02}:00")
11602 }
11603 PeriodFreq::Minutely => {
11604 let day = ord.div_euclid(1440);
11605 let mins = ord.rem_euclid(1440);
11606 let (y, m, d) = civil_from_days(day);
11607 write!(
11608 rendered,
11609 "{y:04}-{m:02}-{d:02} {:02}:{:02}",
11610 mins / 60,
11611 mins % 60
11612 )
11613 }
11614 PeriodFreq::Secondly => {
11615 let day = ord.div_euclid(86_400);
11616 let secs = ord.rem_euclid(86_400);
11617 let (y, m, d) = civil_from_days(day);
11618 write!(
11619 rendered,
11620 "{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02}",
11621 secs / 3600,
11622 (secs % 3600) / 60,
11623 secs % 60
11624 )
11625 }
11626 PeriodFreq::Milliseconds | PeriodFreq::Microseconds | PeriodFreq::Nanoseconds => {
11633 let (per_sec, width) = match self.freq.base() {
11634 PeriodFreq::Milliseconds => (1_000_i64, 3_usize),
11635 PeriodFreq::Microseconds => (1_000_000_i64, 6_usize),
11636 _ => (1_000_000_000_i64, 9_usize),
11637 };
11638 let per_day = 86_400 * per_sec;
11640 let day = ord.div_euclid(per_day);
11641 let rest = ord.rem_euclid(per_day);
11642 let secs = rest / per_sec;
11643 let frac = rest % per_sec;
11644 let (y, m, d) = civil_from_days(day);
11645 write!(
11646 rendered,
11647 "{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02}.{:0width$}",
11648 secs / 3600,
11649 (secs % 3600) / 60,
11650 secs % 60,
11651 frac,
11652 width = width
11653 )
11654 }
11655 PeriodFreq::Multiple(_) => Self::new(ord, self.freq.base()).write_calendar(rendered),
11656 }
11657 }
11658}
11659
11660#[must_use]
11665pub fn civil_from_days(days_since_epoch: i64) -> (i64, u32, u32) {
11666 let days = days_since_epoch + 719_468;
11667 let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
11668 let doe = days - era * 146_097;
11669 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
11670 let y = yoe + era * 400;
11671 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
11672 let mp = (5 * doy + 2) / 153;
11673 let d = doy - (153 * mp + 2) / 5 + 1;
11674 let m = if mp < 10 { mp + 3 } else { mp - 9 };
11675 let year = if m <= 2 { y + 1 } else { y };
11676 (year, m as u32, d as u32)
11677}
11678
11679fn parse_annual_period(value: &str) -> Option<i64> {
11680 (value.len() == 4 && value.chars().all(|ch| ch.is_ascii_digit()))
11681 .then(|| value.parse::<i64>().ok())
11682 .flatten()
11683}
11684
11685fn parse_year_month_period(value: &str) -> Option<(i64, u32)> {
11686 let (year, month) = value.split_once('-')?;
11687 if year.len() != 4 || month.len() != 2 {
11688 return None;
11689 }
11690 let year = year.parse::<i64>().ok()?;
11691 let month = month.parse::<u32>().ok()?;
11692 (1..=12).contains(&month).then_some((year, month))
11693}
11694
11695fn parse_ymd_period(value: &str) -> Option<(i64, u32, u32)> {
11696 let mut parts = value.split('-');
11697 let year = parts.next()?;
11698 let month = parts.next()?;
11699 let day = parts.next()?;
11700 if parts.next().is_some() || year.len() != 4 || month.len() != 2 || day.len() != 2 {
11701 return None;
11702 }
11703 let year = year.parse::<i64>().ok()?;
11704 let month = month.parse::<u32>().ok()?;
11705 let day = day.parse::<u32>().ok()?;
11706 (1..=days_in_month(year, month)?)
11707 .contains(&day)
11708 .then_some((year, month, day))
11709}
11710
11711fn parse_quarter_period(value: &str) -> Option<(i64, u32)> {
11712 let (year, quarter) = value.split_once('Q').or_else(|| value.split_once('q'))?;
11713 if year.len() != 4 || quarter.len() != 1 {
11714 return None;
11715 }
11716 let year = year.parse::<i64>().ok()?;
11717 let quarter = quarter.parse::<u32>().ok()?;
11718 (1..=4).contains(&quarter).then_some((year, quarter))
11719}
11720
11721impl std::fmt::Display for Period {
11722 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
11725 self.write_calendar(f)
11726 }
11727}
11728
11729#[must_use]
11748pub fn period_range(start: Period, periods: usize) -> Vec<Period> {
11749 (0..periods).map(|i| start.shift(i as i64)).collect()
11750}
11751
11752#[cfg(test)]
11753mod tests {
11754 use super::{
11755 DType, Interval, IntervalClosed, NullKind, Period, PeriodFreq, Scalar, SparseDType,
11756 cast_scalar, common_dtype, infer_dtype,
11757 };
11758
11759 struct Named(&'static str);
11762
11763 impl super::HostObject for Named {
11764 fn host_eq(&self, other: &dyn super::HostObject) -> bool {
11765 other
11766 .as_any()
11767 .downcast_ref::<Named>()
11768 .is_some_and(|other| other.0 == self.0)
11769 }
11770 fn host_repr(&self) -> String {
11771 format!("Named({:?})", self.0)
11772 }
11773 fn host_str(&self) -> String {
11774 self.0.to_owned()
11775 }
11776 fn host_hash(&self) -> Option<u64> {
11777 (!self.0.is_empty()).then_some(self.0.len() as u64)
11778 }
11779 fn host_cmp(&self, other: &dyn super::HostObject) -> Option<std::cmp::Ordering> {
11781 let other = other.as_any().downcast_ref::<Named>()?;
11782 (!self.0.starts_with('!') && !other.0.starts_with('!')).then(|| self.0.cmp(other.0))
11783 }
11784 fn as_any(&self) -> &dyn std::any::Any {
11785 self
11786 }
11787 }
11788
11789 #[test]
11790 fn host_values_block_workers_only_under_a_declared_host_lock_4qg5w_13() {
11791 use std::sync::atomic::Ordering;
11792
11793 use super::{HostValue, LIVE_HOST_VALUES, workers_blocked};
11794 assert!(workers_blocked(true, 1));
11798 assert!(!workers_blocked(true, 0));
11799 assert!(!workers_blocked(false, 3));
11800 let first = HostValue::new(Named("held"));
11805 assert!(LIVE_HOST_VALUES.load(Ordering::Relaxed) > 0);
11806 let clone = first.clone();
11807 drop(first);
11808 assert!(LIVE_HOST_VALUES.load(Ordering::Relaxed) > 0);
11809 assert_eq!(clone.object().host_str(), "held");
11810 }
11811
11812 #[test]
11813 fn object_cells_order_like_python_then_totally_fvsao_66() {
11814 use std::cmp::Ordering;
11815
11816 use super::{HostValue, ObjectValue};
11817 let host = |name: &'static str| ObjectValue::Host(HostValue::new(Named(name)));
11818 let list = |items: Vec<Scalar>| ObjectValue::list(items);
11819 assert_eq!(host("a").python_cmp(&host("b")), Some(Ordering::Less));
11822 assert!(host("b") > host("a"));
11823 assert_eq!(host("a").cmp(&host("a")), Ordering::Equal);
11824 let one_ten = list(vec![Scalar::Int64(1), Scalar::Int64(10)]);
11827 let one_two = list(vec![Scalar::Int64(1), Scalar::Int64(2)]);
11828 assert_eq!(one_two.python_cmp(&one_ten), Some(Ordering::Less));
11829 assert!(list(vec![Scalar::Int64(1)]) < one_two);
11830 let mixed = list(vec![Scalar::Float64(1.0), Scalar::Int64(3)]);
11832 assert_eq!(one_two.python_cmp(&mixed), Some(Ordering::Less));
11833 assert_eq!(one_two.python_cmp(&host("a")), None);
11836 assert!(one_two < host("a"));
11837 assert_eq!(host("!z").python_cmp(&host("!a")), None);
11838 assert!(host("!a") < host("!z"));
11839 let text = list(vec![Scalar::Utf8("a".to_owned())]);
11840 assert_eq!(one_two.python_cmp(&text), None);
11841 assert_ne!(one_two.cmp(&text), Ordering::Equal);
11842 let nan = || list(vec![Scalar::Float64(f64::NAN)]);
11845 let (first, second) = (nan(), nan());
11846 assert_ne!(first, second);
11847 assert_ne!(first.cmp(&second), Ordering::Equal);
11848 assert_eq!(first.cmp(&second), second.cmp(&first).reverse());
11849 }
11850
11851 #[test]
11852 fn bytes_cells_print_order_and_serialize_like_python_bytes_4qg5w_8() {
11853 use std::cmp::Ordering;
11854
11855 use super::ObjectValue;
11856 let bytes = |data: &[u8]| Scalar::Object(ObjectValue::bytes(data.to_vec()));
11857 assert_eq!(bytes(b"ab").python_repr(), "b'ab'");
11860 assert_eq!(bytes(b"a'b").python_repr(), "b\"a'b\"");
11861 assert_eq!(bytes(b"a'\"").python_repr(), "b'a\\'\"'");
11862 assert_eq!(bytes(b"\x00\t\\\xff").python_repr(), "b'\\x00\\t\\\\\\xff'");
11863 assert_eq!(bytes(b"ab").python_type_name(), "bytes");
11864 assert_eq!(bytes(b"ab").python_cmp(&bytes(b"b")), Some(Ordering::Less));
11866 assert_eq!(bytes(b"a").python_cmp(&bytes(b"ab")), Some(Ordering::Less));
11867 assert_eq!(bytes(b"a").python_cmp(&Scalar::Utf8("a".to_owned())), None);
11868 assert_ne!(bytes(b"a"), Scalar::Utf8("a".to_owned()));
11869 assert!(!bytes(b"").to_bool().unwrap());
11870 let json = serde_json::to_string(&bytes(b"hi")).unwrap();
11872 assert_eq!(json, r#"{"kind":"object","value":{"bytes":[104,105]}}"#);
11873 let back: Scalar = serde_json::from_str(&json).unwrap();
11874 assert_eq!(back, bytes(b"hi"));
11875 let list: Scalar =
11877 serde_json::from_str(r#"{"kind":"object","value":[{"kind":"int64","value":1}]}"#)
11878 .unwrap();
11879 assert_eq!(
11880 list,
11881 Scalar::Object(ObjectValue::list(vec![Scalar::Int64(1)]))
11882 );
11883 }
11884
11885 #[test]
11886 fn values_order_and_name_their_types_as_python_does_fvsao_71() {
11887 use std::cmp::Ordering;
11888
11889 use super::{HostValue, ObjectValue};
11890 let text = |value: &str| Scalar::Utf8(value.to_owned());
11891 let host =
11892 |name: &'static str| Scalar::Object(ObjectValue::Host(HostValue::new(Named(name))));
11893 let list = |items: Vec<Scalar>| Scalar::Object(ObjectValue::list(items));
11894 assert_eq!(
11897 Scalar::Bool(true).python_cmp(&Scalar::Float64(1.5)),
11898 Some(Ordering::Less)
11899 );
11900 assert_eq!(
11901 Scalar::Int64(2).python_cmp(&Scalar::Float64(2.0)),
11902 Some(Ordering::Equal)
11903 );
11904 assert_eq!(text("b").python_cmp(&text("a")), Some(Ordering::Greater));
11905 assert_eq!(
11906 Scalar::Datetime64(5).python_cmp(&Scalar::Datetime64(9)),
11907 Some(Ordering::Less)
11908 );
11909 let interval = |left: f64, right: f64| {
11910 Scalar::Interval(Interval::new(left, right, IntervalClosed::Right))
11911 };
11912 assert_eq!(
11913 interval(0.0, 5.0).python_cmp(&interval(0.0, 2.0)),
11914 Some(Ordering::Greater)
11915 );
11916 assert_eq!(host("a").python_cmp(&host("b")), Some(Ordering::Less));
11917 assert_eq!(text("a").python_cmp(&Scalar::Int64(1)), None);
11920 assert_eq!(
11921 Scalar::Datetime64(1).python_cmp(&Scalar::Timedelta64(1)),
11922 None
11923 );
11924 assert_eq!(host("a").python_cmp(&Scalar::Int64(1)), None);
11925 assert_eq!(host("!a").python_cmp(&host("b")), None);
11926 assert_eq!(text("a").python_type_name(), "str");
11930 assert_eq!(Scalar::Bool(true).python_type_name(), "bool");
11931 assert_eq!(Scalar::Datetime64(1).python_type_name(), "Timestamp");
11932 assert_eq!(list(vec![]).python_type_name(), "list");
11933 assert_eq!(host("a").python_type_name(), "object");
11934 let (left, right) = list(vec![Scalar::Int64(1), Scalar::Int64(2)])
11935 .python_cmp_type_names(&list(vec![Scalar::Int64(1), text("x")]));
11936 assert_eq!((left.as_str(), right.as_str()), ("int", "str"));
11937 let (left, right) = text("a").python_cmp_type_names(&list(vec![]));
11938 assert_eq!((left.as_str(), right.as_str()), ("str", "list"));
11939 }
11940
11941 #[test]
11942 fn object_cells_print_compare_and_hash_like_python_fvsao_33() {
11943 use std::hash::{Hash, Hasher};
11944
11945 use super::{HostValue, ObjectValue};
11946 let hash = |value: &ObjectValue| {
11947 let mut hasher = std::collections::hash_map::DefaultHasher::new();
11948 value.hash(&mut hasher);
11949 hasher.finish()
11950 };
11951 let list = ObjectValue::list(vec![
11952 Scalar::Int64(1),
11953 Scalar::Utf8("a".to_owned()),
11954 Scalar::Null(NullKind::Null),
11955 Scalar::Float64(2.0),
11956 Scalar::Object(ObjectValue::list(vec![Scalar::Utf8("b".to_owned())])),
11957 ]);
11958 assert_eq!(list.repr(), "[1, 'a', None, 2.0, ['b']]");
11961 assert_eq!(list.to_string(), "[1, 'a', None, 2.0, ['b']]");
11962 assert_eq!(list.pprint(), "[1, a, None, 2.0, [b]]");
11963 assert_eq!(Scalar::Object(list.clone()).dtype(), DType::Utf8);
11965 assert!(!Scalar::Object(list.clone()).is_missing());
11966 let same = ObjectValue::list(list.as_list().unwrap().to_vec());
11969 assert_eq!(list, same);
11970 assert_eq!(hash(&list), hash(&same));
11971 let other = ObjectValue::list(vec![Scalar::Int64(1)]);
11972 assert_ne!(list, other);
11973 let host = ObjectValue::Host(HostValue::new(Named("x")));
11974 assert_ne!(list, host);
11975 assert_eq!(host, ObjectValue::Host(HostValue::new(Named("x"))));
11977 assert_ne!(host, ObjectValue::Host(HostValue::new(Named("y"))));
11978 assert_eq!(host.repr(), "Named(\"x\")");
11979 assert_eq!(host.to_string(), "x");
11980 assert!(
11982 !Scalar::Object(ObjectValue::list(Vec::new()))
11983 .to_bool()
11984 .unwrap()
11985 );
11986 assert!(Scalar::Object(host.clone()).to_bool().unwrap());
11987 assert!(Scalar::Object(list.clone()).to_f64().is_err());
11989 let json = serde_json::to_string(&Scalar::Object(other.clone())).unwrap();
11992 assert_eq!(
11993 serde_json::from_str::<Scalar>(&json).unwrap(),
11994 Scalar::Object(other)
11995 );
11996 assert!(serde_json::to_string(&Scalar::Object(host)).is_err());
11997 }
11998
11999 #[test]
12000 fn a_host_cell_displays_by_its_pprint_and_stringifies_by_its_str() {
12001 use super::{HostValue, ObjectValue};
12002
12003 struct Pair;
12005 impl super::HostObject for Pair {
12006 fn host_eq(&self, _other: &dyn super::HostObject) -> bool {
12007 false
12008 }
12009 fn host_repr(&self) -> String {
12010 "('a', 1)".to_owned()
12011 }
12012 fn host_str(&self) -> String {
12013 "('a', 1)".to_owned()
12014 }
12015 fn host_pprint(&self) -> String {
12016 "(a, 1)".to_owned()
12017 }
12018 fn host_hash(&self) -> Option<u64> {
12019 None
12020 }
12021 fn host_cmp(&self, _other: &dyn super::HostObject) -> Option<std::cmp::Ordering> {
12022 None
12023 }
12024 fn as_any(&self) -> &dyn std::any::Any {
12025 self
12026 }
12027 }
12028 let pair = ObjectValue::Host(HostValue::new(Pair));
12029 assert_eq!(pair.pprint(), "(a, 1)");
12030 let list = ObjectValue::list(vec![Scalar::Object(pair.clone())]);
12032 assert_eq!(list.pprint(), "[(a, 1)]");
12033 assert_eq!(pair.to_string(), "('a', 1)");
12035 let named = ObjectValue::Host(HostValue::new(Named("x")));
12037 assert_eq!(named.pprint(), "x");
12038 }
12039
12040 #[test]
12041 fn float64_json_spells_infinity_and_round_trips() {
12042 let json = |s: &Scalar| serde_json::to_string(s).expect("serialize");
12046 let back = |text: &str| serde_json::from_str::<Scalar>(text);
12047 assert_eq!(
12048 json(&Scalar::Float64(f64::INFINITY)),
12049 r#"{"kind":"float64","value":"inf"}"#
12050 );
12051 assert_eq!(
12052 json(&Scalar::Float64(f64::NEG_INFINITY)),
12053 r#"{"kind":"float64","value":"-inf"}"#
12054 );
12055 assert_eq!(
12057 json(&Scalar::Float64(1.5)),
12058 r#"{"kind":"float64","value":1.5}"#
12059 );
12060 assert_eq!(
12061 json(&Scalar::Float64(-0.0)),
12062 r#"{"kind":"float64","value":-0.0}"#
12063 );
12064 assert_eq!(
12065 json(&Scalar::Float64(f64::NAN)),
12066 r#"{"kind":"float64","value":null}"#
12067 );
12068 for value in [f64::INFINITY, f64::NEG_INFINITY, 1.5, -2.25e300] {
12069 let scalar = Scalar::Float64(value);
12070 assert_eq!(back(&json(&scalar)).expect("round trip"), scalar);
12071 }
12072 let negative_zero = back(r#"{"kind":"float64","value":-0.0}"#).expect("-0.0");
12073 assert!(matches!(negative_zero, Scalar::Float64(v) if v == 0.0 && v.is_sign_negative()));
12074 assert!(matches!(
12075 back(r#"{"kind":"float64","value":null}"#).expect("null"),
12076 Scalar::Float64(v) if v.is_nan()
12077 ));
12078 assert!(back(r#"{"kind":"float64","value":"Infinity"}"#).is_err());
12080 assert!(back(r#"{"kind":"float64","value":"1.5"}"#).is_err());
12081 }
12082
12083 #[test]
12093 fn semantic_cmp_cross_numeric_int_float_cdpai() {
12094 use std::cmp::Ordering;
12097 let mut st: u64 = 0xc205_a1b2_c3d4_e5f6;
12098 let mut next = || {
12099 st = st
12100 .wrapping_mul(6_364_136_223_846_793_005)
12101 .wrapping_add(1_442_695_040_888_963_407);
12102 (st >> 33) as u32
12103 };
12104 for _ in 0..3000u32 {
12105 let i = (next() % 21) as i64 - 10;
12106 let f = (next() % 400) as f64 / 20.0 - 10.0; let exp = (i as f64).partial_cmp(&f).unwrap();
12108 assert_eq!(Scalar::Int64(i).semantic_cmp(&Scalar::Float64(f)), exp);
12109 assert_eq!(
12110 Scalar::Float64(f).semantic_cmp(&Scalar::Int64(i)),
12111 exp.reverse()
12112 );
12113 }
12114 assert_eq!(
12116 Scalar::Int64(5).semantic_cmp(&Scalar::Float64(5.0)),
12117 Ordering::Equal
12118 );
12119 assert_eq!(
12120 Scalar::Float64(5.0).semantic_cmp(&Scalar::Int64(5)),
12121 Ordering::Equal
12122 );
12123 assert_eq!(
12124 Scalar::Int64(3).semantic_cmp(&Scalar::Float64(3.5)),
12125 Ordering::Less
12126 );
12127 assert_eq!(
12128 Scalar::Int64(4).semantic_cmp(&Scalar::Float64(3.5)),
12129 Ordering::Greater
12130 );
12131 }
12132
12133 #[test]
12134 fn semantic_cmp_nat_degeneracy_temporal_767ak() {
12135 use std::cmp::Ordering;
12136 const NAT: i64 = i64::MIN;
12137
12138 let td_nat = Scalar::Timedelta64(NAT);
12140 for v in [-3i64, 0, 5, 99] {
12141 let td = Scalar::Timedelta64(v);
12142 assert_eq!(td_nat.semantic_cmp(&td), Ordering::Equal, "td NAT vs {v}");
12143 assert_eq!(td.semantic_cmp(&td_nat), Ordering::Equal, "td {v} vs NAT");
12144 }
12145 assert_eq!(td_nat.semantic_cmp(&td_nat), Ordering::Equal);
12146
12147 let dt_nat = Scalar::Datetime64(NAT);
12149 for v in [-3i64, 0, 5, 99] {
12150 let dt = Scalar::Datetime64(v);
12151 assert_eq!(dt_nat.semantic_cmp(&dt), Ordering::Equal, "dt NAT vs {v}");
12152 assert_eq!(dt.semantic_cmp(&dt_nat), Ordering::Equal, "dt {v} vs NAT");
12153 }
12154 assert_eq!(dt_nat.semantic_cmp(&dt_nat), Ordering::Equal);
12155
12156 for (a, b) in [(1i64, 2i64), (5, 5), (9, -1)] {
12158 let (ta, tb) = (Scalar::Timedelta64(a), Scalar::Timedelta64(b));
12159 assert_eq!(ta.semantic_cmp(&ta), Ordering::Equal);
12160 assert_eq!(ta.semantic_cmp(&tb), b.cmp(&a).reverse()); assert_eq!(ta.semantic_cmp(&tb), a.cmp(&b));
12162 let (da, db) = (Scalar::Datetime64(a), Scalar::Datetime64(b));
12163 assert_eq!(da.semantic_cmp(&db), a.cmp(&b));
12164 }
12165 }
12166
12167 fn semantic_cmp_cross_variant_values_d5ikg() -> [Scalar; 9] {
12168 [
12169 Scalar::Null(NullKind::Null),
12170 Scalar::Bool(true),
12171 Scalar::Int64(-7),
12172 Scalar::Float64(3.5),
12173 Scalar::Utf8("mixed".to_owned()),
12174 Scalar::Timedelta64(11),
12175 Scalar::Datetime64(1_735_732_800_123_456_789),
12176 Scalar::Period(Period::new(649, PeriodFreq::Monthly)),
12177 Scalar::Interval(Interval::new(-1.5, 2.5, IntervalClosed::Right)),
12178 ]
12179 }
12180
12181 fn semantic_cmp_uses_debug_fallback_d5ikg(left: &Scalar, right: &Scalar) -> bool {
12182 !matches!(
12183 (left, right),
12184 (Scalar::Int64(_), Scalar::Float64(_)) | (Scalar::Float64(_), Scalar::Int64(_))
12185 )
12186 }
12187
12188 #[test]
12189 fn semantic_cmp_cross_variant_matches_debug_order_d5ikg() {
12190 let values = semantic_cmp_cross_variant_values_d5ikg();
12191 for (left_index, left) in values.iter().enumerate() {
12192 for (right_index, right) in values.iter().enumerate() {
12193 if left_index != right_index && semantic_cmp_uses_debug_fallback_d5ikg(left, right)
12194 {
12195 assert_eq!(
12196 left.semantic_cmp(right),
12197 format!("{left:?}").cmp(&format!("{right:?}")),
12198 "cross-variant order mismatch: {left:?} vs {right:?}"
12199 );
12200 }
12201 }
12202 }
12203 }
12204
12205 #[test]
12206 #[ignore = "foreground release attribution harness"]
12207 fn semantic_cmp_cross_variant_debug_alloc_ab_d5ikg() {
12208 use std::cmp::Ordering;
12209
12210 const BATCH: usize = 4_096;
12211 const BLOCKS: usize = 9;
12212
12213 fn former(left: &Scalar, right: &Scalar) -> Ordering {
12214 format!("{left:?}").cmp(&format!("{right:?}"))
12215 }
12216
12217 fn candidate(left: &Scalar, right: &Scalar) -> Ordering {
12218 left.semantic_cmp(right)
12219 }
12220
12221 fn elapsed(values: &[Scalar], compare: fn(&Scalar, &Scalar) -> Ordering) -> u128 {
12222 let mut less = 0usize;
12223 let started = std::time::Instant::now();
12224 for _ in 0..BATCH {
12225 for (left_index, left) in values.iter().enumerate() {
12226 for (right_index, right) in values.iter().enumerate() {
12227 if left_index != right_index
12228 && semantic_cmp_uses_debug_fallback_d5ikg(left, right)
12229 && compare(std::hint::black_box(left), std::hint::black_box(right))
12230 == Ordering::Less
12231 {
12232 less += 1;
12233 }
12234 }
12235 }
12236 }
12237 std::hint::black_box(less);
12238 started.elapsed().as_nanos()
12239 }
12240
12241 fn median(samples: &mut [u128]) -> u128 {
12242 samples.sort_unstable();
12243 samples[samples.len() / 2]
12244 }
12245
12246 let values = semantic_cmp_cross_variant_values_d5ikg();
12247
12248 for (left_index, left) in values.iter().enumerate() {
12249 for (right_index, right) in values.iter().enumerate() {
12250 if left_index != right_index && semantic_cmp_uses_debug_fallback_d5ikg(left, right)
12251 {
12252 assert_eq!(
12253 former(left, right),
12254 candidate(left, right),
12255 "cross-variant order mismatch: {left:?} vs {right:?}"
12256 );
12257 }
12258 }
12259 }
12260
12261 std::hint::black_box(elapsed(&values, former));
12262 std::hint::black_box(elapsed(&values, candidate));
12263
12264 let mut former_samples = Vec::with_capacity(BLOCKS * 2);
12265 let mut candidate_samples = Vec::with_capacity(BLOCKS * 2);
12266 for block in 0..BLOCKS {
12267 if block.is_multiple_of(2) {
12268 former_samples.push(elapsed(&values, former));
12269 candidate_samples.push(elapsed(&values, candidate));
12270 candidate_samples.push(elapsed(&values, candidate));
12271 former_samples.push(elapsed(&values, former));
12272 } else {
12273 candidate_samples.push(elapsed(&values, candidate));
12274 former_samples.push(elapsed(&values, former));
12275 former_samples.push(elapsed(&values, former));
12276 candidate_samples.push(elapsed(&values, candidate));
12277 }
12278 }
12279
12280 let former_p50 = median(&mut former_samples);
12281 let candidate_p50 = median(&mut candidate_samples);
12282 eprintln!(
12283 "semantic_cmp_cross_variant_debug_alloc former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} speedup={:.6}",
12284 former_p50 as f64 / candidate_p50 as f64
12285 );
12286 }
12287
12288 #[test]
12289 fn semantic_cmp_total_order_axioms_ay8o9() {
12290 use std::cmp::Ordering;
12291
12292 let mut state: u64 = 0xc0ff_eeba_df00_d123;
12293 let mut next = || {
12294 state = state
12295 .wrapping_mul(6_364_136_223_846_793_005)
12296 .wrapping_add(1_442_695_040_888_963_407);
12297 (state >> 33) as u32
12298 };
12299
12300 for iter in 0..6000u32 {
12301 let dt = next() % 4;
12302 let mk = |r: u32| match dt {
12304 0 => Scalar::Int64((r % 11) as i64 - 5),
12305 1 => Scalar::Float64(f64::from((r % 21) as i32 - 10) / 2.0),
12307 2 => Scalar::Utf8(format!("s{}", r % 5)),
12308 _ => Scalar::Bool(r.is_multiple_of(2)),
12309 };
12310 let a = mk(next());
12311 let b = mk(next());
12312 let c = mk(next());
12313 let ctx = format!("iter={iter} a={a:?} b={b:?} c={c:?}");
12314
12315 assert_eq!(a.semantic_cmp(&a), Ordering::Equal, "reflexive {ctx}");
12317 assert_eq!(
12319 a.semantic_cmp(&b),
12320 b.semantic_cmp(&a).reverse(),
12321 "antisymmetric {ctx}"
12322 );
12323 let ab = a.semantic_cmp(&b);
12325 assert_eq!(
12326 a.semantic_le(&b),
12327 ab != Ordering::Greater,
12328 "le-consistent {ctx}"
12329 );
12330 assert_eq!(
12331 a.semantic_ge(&b),
12332 ab != Ordering::Less,
12333 "ge-consistent {ctx}"
12334 );
12335 assert_eq!(
12336 a.semantic_le(&b) && a.semantic_ge(&b),
12337 ab == Ordering::Equal,
12338 "le&ge<=>eq {ctx}"
12339 );
12340 if a.semantic_cmp(&b) != Ordering::Greater && b.semantic_cmp(&c) != Ordering::Greater {
12342 assert_ne!(a.semantic_cmp(&c), Ordering::Greater, "transitivity {ctx}");
12343 }
12344 }
12345
12346 let nan = Scalar::Float64(f64::NAN);
12350 for v in [
12351 Scalar::Float64(-3.5),
12352 Scalar::Float64(0.0),
12353 Scalar::Float64(7.25),
12354 ] {
12355 assert_eq!(nan.semantic_cmp(&v), Ordering::Equal, "NaN cmp finite");
12356 assert_eq!(v.semantic_cmp(&nan), Ordering::Equal, "finite cmp NaN");
12357 }
12358 assert_eq!(nan.semantic_cmp(&nan), Ordering::Equal, "NaN cmp NaN");
12359 }
12360
12361 #[test]
12367 fn common_dtype_lattice_axioms_be314() {
12368 let all: [DType; 14] = [
12369 DType::Null,
12370 DType::Bool,
12371 DType::BoolNullable,
12372 DType::Int64,
12373 DType::Int64Nullable,
12374 DType::Float64,
12375 DType::Float64Nullable,
12378 DType::Utf8,
12379 DType::Categorical,
12380 DType::Timedelta64,
12381 DType::datetime64_naive(),
12382 DType::Period,
12383 DType::Interval,
12384 DType::Sparse,
12385 ];
12386
12387 for a in &all {
12388 assert_eq!(
12390 common_dtype(a.clone(), a.clone()),
12391 Ok(a.clone()),
12392 "idempotent {a:?}"
12393 );
12394 assert_eq!(
12396 common_dtype(DType::Null, a.clone()),
12397 Ok(a.clone()),
12398 "null-left identity {a:?}"
12399 );
12400 assert_eq!(
12401 common_dtype(a.clone(), DType::Null),
12402 Ok(a.clone()),
12403 "null-right identity {a:?}"
12404 );
12405
12406 for b in &all {
12407 assert_eq!(
12410 common_dtype(a.clone(), b.clone()).ok(),
12411 common_dtype(b.clone(), a.clone()).ok(),
12412 "commutative value {a:?},{b:?}"
12413 );
12414 assert_eq!(
12415 common_dtype(a.clone(), b.clone()).is_ok(),
12416 common_dtype(b.clone(), a.clone()).is_ok(),
12417 "commutative ok-ness {a:?},{b:?}"
12418 );
12419 }
12420 }
12421
12422 for a in &all {
12425 for b in &all {
12426 for c in &all {
12427 if let (Ok(ab), Ok(bc)) = (
12428 common_dtype(a.clone(), b.clone()),
12429 common_dtype(b.clone(), c.clone()),
12430 ) && let (Ok(left), Ok(right)) =
12431 (common_dtype(ab, c.clone()), common_dtype(a.clone(), bc))
12432 {
12433 assert_eq!(left, right, "associative {a:?},{b:?},{c:?}");
12434 }
12435 }
12436 }
12437 }
12438 }
12439
12440 #[test]
12443 fn infer_dtype_coercion_rules_e3sfq() {
12444 use DType::{Bool, Float64, Int64, Null, Utf8};
12445
12446 assert_eq!(infer_dtype(&[]), Ok(Null));
12448 assert_eq!(
12449 infer_dtype(&[Scalar::Null(NullKind::Null), Scalar::Null(NullKind::NaN)]),
12450 Ok(Null)
12451 );
12452
12453 let mut s: u64 = 0x132d_a7e0_0e3f_c0de;
12455 let mut next = || {
12456 s = s
12457 .wrapping_mul(6_364_136_223_846_793_005)
12458 .wrapping_add(1_442_695_040_888_963_407);
12459 (s >> 33) as u32
12460 };
12461 for _ in 0..600u32 {
12462 let n = (next() % 6) as usize + 1;
12463 let ints: Vec<Scalar> = (0..n)
12464 .map(|_| Scalar::Int64((next() % 9) as i64 - 4))
12465 .collect();
12466 assert_eq!(infer_dtype(&ints), Ok(Int64));
12467 let floats: Vec<Scalar> = (0..n)
12468 .map(|_| Scalar::Float64(f64::from((next() % 7) as i32)))
12469 .collect();
12470 assert_eq!(infer_dtype(&floats), Ok(Float64));
12471 let bools: Vec<Scalar> = (0..n).map(|_| Scalar::Bool(next() % 2 == 0)).collect();
12472 assert_eq!(infer_dtype(&bools), Ok(Bool));
12473 let strs: Vec<Scalar> = (0..n)
12474 .map(|_| Scalar::Utf8(format!("s{}", next() % 4)))
12475 .collect();
12476 assert_eq!(infer_dtype(&strs), Ok(Utf8));
12477 }
12478
12479 assert_eq!(
12481 infer_dtype(&[
12482 Scalar::Int64(1),
12483 Scalar::Null(NullKind::Null),
12484 Scalar::Int64(2)
12485 ]),
12486 Ok(Int64),
12487 "Int64 + nulls -> Int64"
12488 );
12489 assert_eq!(
12490 infer_dtype(&[Scalar::Int64(1), Scalar::Float64(2.5)]),
12491 Ok(Float64),
12492 "Int64 + Float64 -> Float64"
12493 );
12494 assert_eq!(
12498 infer_dtype(&[Scalar::Bool(true), Scalar::Int64(3)]),
12499 Ok(Utf8),
12500 "Bool + Int64 -> object bucket (pandas constructs object)"
12501 );
12502 assert_eq!(
12503 infer_dtype(&[Scalar::Utf8("a".into()), Scalar::Int64(3)]),
12504 Ok(Utf8),
12505 "Utf8 + Int64 -> Utf8 (object fallback)"
12506 );
12507 }
12508
12509 #[test]
12514 fn missing_for_dtype_always_missing_1ews0() {
12515 let all: [DType; 14] = [
12516 DType::Null,
12517 DType::Bool,
12518 DType::BoolNullable,
12519 DType::Int64,
12520 DType::Int64Nullable,
12521 DType::Float64,
12522 DType::Float64Nullable,
12523 DType::Utf8,
12524 DType::Categorical,
12525 DType::Timedelta64,
12526 DType::datetime64_naive(),
12527 DType::Period,
12528 DType::Interval,
12529 DType::Sparse,
12530 ];
12531 for dt in &all {
12532 let m = Scalar::missing_for_dtype(dt.clone());
12533 assert!(m.is_missing(), "missing_for_dtype({dt:?}) must be missing");
12534 for target in &all {
12535 let cast = cast_scalar(&m, target.clone()).expect("cast of missing");
12536 if target == &DType::Utf8 {
12537 assert!(
12540 matches!(cast, Scalar::Utf8(_)),
12541 "cast(missing {dt:?} -> Utf8) yields a string, got {cast:?}"
12542 );
12543 } else if matches!(dt, DType::Timedelta64 | DType::Datetime64 { .. })
12544 && matches!(target, DType::Bool | DType::Int64)
12545 {
12546 match target {
12562 DType::Bool => assert_eq!(
12563 cast,
12564 Scalar::Bool(true),
12565 "cast(missing {dt:?} -> Bool) is pandas' nonzero-truthy \
12566 read of the NaT bits"
12567 ),
12568 _ => assert_eq!(
12569 cast,
12570 Scalar::Int64(i64::MIN),
12571 "cast(missing {dt:?} -> Int64) is the NaT sentinel itself"
12572 ),
12573 }
12574 } else {
12575 assert!(
12578 cast.is_missing(),
12579 "cast(missing {dt:?} -> {target:?}) must stay missing, got {cast:?}"
12580 );
12581 }
12582 }
12583 }
12584 }
12585
12586 #[test]
12587 fn cast_scalar_bool_int_roundtrip_6w07b() {
12588 use super::cast_scalar;
12589 assert_eq!(
12591 cast_scalar(&Scalar::Bool(true), DType::Int64).unwrap(),
12592 Scalar::Int64(1)
12593 );
12594 assert_eq!(
12595 cast_scalar(&Scalar::Bool(false), DType::Int64).unwrap(),
12596 Scalar::Int64(0)
12597 );
12598 assert_eq!(
12599 cast_scalar(&Scalar::Int64(0), DType::Bool).unwrap(),
12600 Scalar::Bool(false)
12601 );
12602 let mut st: u64 = 0x4b07_0b1c_2d3e_4f50;
12603 let mut next = || {
12604 st = st
12605 .wrapping_mul(6_364_136_223_846_793_005)
12606 .wrapping_add(1_442_695_040_888_963_407);
12607 (st >> 33) as u32
12608 };
12609 for _ in 0..2000u32 {
12610 let v = (next() % 21) as i64 - 10;
12611 assert_eq!(
12612 cast_scalar(&Scalar::Int64(v), DType::Bool).unwrap(),
12613 Scalar::Bool(v != 0),
12614 "int->bool v={v}"
12615 );
12616 }
12617 }
12618
12619 #[test]
12621 fn cast_scalar_float_to_int_truncates_toward_zero_u9lec() {
12622 use super::cast_scalar;
12623 let mut st: u64 = 0x4ca5_0b1c_2d3e_4f50;
12626 let mut next = || {
12627 st = st
12628 .wrapping_mul(6_364_136_223_846_793_005)
12629 .wrapping_add(1_442_695_040_888_963_407);
12630 (st >> 33) as u32
12631 };
12632 for (f, exp) in [
12634 (-3.7, -3i64),
12635 (3.7, 3),
12636 (-3.2, -3),
12637 (3.2, 3),
12638 (-0.9, 0),
12639 (0.9, 0),
12640 (-5.0, -5),
12641 (5.0, 5),
12642 ] {
12643 assert_eq!(
12644 cast_scalar(&Scalar::Float64(f), DType::Int64).unwrap(),
12645 Scalar::Int64(exp),
12646 "cast {f}"
12647 );
12648 }
12649 for _ in 0..3000u32 {
12651 let v = (next() % 2_000_001) as f64 / 1000.0 - 1000.0; let got = cast_scalar(&Scalar::Float64(v), DType::Int64).unwrap();
12653 assert_eq!(
12654 got,
12655 Scalar::Int64(v.trunc() as i64),
12656 "trunc-toward-zero v={v}"
12657 );
12658 }
12659 }
12660
12661 #[test]
12670 fn cast_scalar_float_to_temporal_truncates_to_nanoseconds() {
12671 use super::{Timedelta, Timestamp, cast_scalar};
12672
12673 for (input, want) in [
12676 (1.5_f64, 1_i64),
12677 (-1.5, -1),
12678 (0.9, 0),
12679 (-0.9, 0),
12680 (2.5, 2),
12681 (-2.5, -2),
12682 (1.999_999, 1),
12683 (-1.999_999, -1),
12684 (2.0, 2),
12685 (1e18, 1_000_000_000_000_000_000),
12686 ] {
12687 assert_eq!(
12688 cast_scalar(&Scalar::Float64(input), DType::datetime64_naive()).unwrap(),
12689 Scalar::Datetime64(want),
12690 "datetime64 cast of {input}"
12691 );
12692 assert_eq!(
12693 cast_scalar(&Scalar::Float64(input), DType::Timedelta64).unwrap(),
12694 Scalar::Timedelta64(want),
12695 "timedelta64 cast of {input}"
12696 );
12697 }
12698
12699 for input in [
12703 f64::NAN,
12704 f64::INFINITY,
12705 f64::NEG_INFINITY,
12706 1e30,
12707 -1e30,
12708 9.3e18,
12709 -9.3e18,
12710 9_223_372_036_854_775_808.0, -9_223_372_036_854_775_808.0, ] {
12713 assert_eq!(
12714 cast_scalar(&Scalar::Float64(input), DType::datetime64_naive()).unwrap(),
12715 Scalar::Datetime64(Timestamp::NAT),
12716 "datetime64 cast of {input} must be NaT"
12717 );
12718 assert_eq!(
12719 cast_scalar(&Scalar::Float64(input), DType::Timedelta64).unwrap(),
12720 Scalar::Timedelta64(Timedelta::NAT),
12721 "timedelta64 cast of {input} must be NaT"
12722 );
12723 }
12724
12725 let just_inside = 9_223_372_036_854_774_784.0_f64; assert_eq!(
12729 cast_scalar(&Scalar::Float64(just_inside), DType::datetime64_naive()).unwrap(),
12730 Scalar::Datetime64(9_223_372_036_854_774_784),
12731 "the largest representable float must NOT be treated as NaT"
12732 );
12733
12734 assert_eq!(
12737 cast_scalar(&Scalar::Float64(1.5), DType::datetime64_naive()).unwrap(),
12738 Scalar::Datetime64(1)
12739 );
12740 assert_eq!(
12741 cast_scalar(&Scalar::Float64(1.5), DType::Int64).unwrap(),
12742 Scalar::Int64(1),
12743 "the SHARED cast truncates here too; it is the explicit constructor \
12744 that refuses, via Column::new's LossyFloatToInt pre-check"
12745 );
12746 }
12747
12748 #[test]
12753 fn cast_scalar_temporal_to_int64_is_raw_nanoseconds() {
12754 use super::{Timedelta, Timestamp, cast_scalar};
12755
12756 for nanos in [1_710_498_645_123_456_789_i64, 93_784_005_006_007, 0, -1] {
12759 assert_eq!(
12760 cast_scalar(&Scalar::Datetime64(nanos), DType::Int64).unwrap(),
12761 Scalar::Int64(nanos),
12762 "datetime64 -> int64 must be the raw nanos ({nanos})"
12763 );
12764 assert_eq!(
12765 cast_scalar(&Scalar::Timedelta64(nanos), DType::Int64).unwrap(),
12766 Scalar::Int64(nanos)
12767 );
12768 }
12769
12770 assert_eq!(
12776 cast_scalar(&Scalar::Datetime64(Timestamp::NAT), DType::Int64).unwrap(),
12777 Scalar::Int64(i64::MIN),
12778 "NaT -> int64 is the sentinel i64::MIN, not a missing value"
12779 );
12780 assert_eq!(
12781 cast_scalar(&Scalar::Timedelta64(Timedelta::NAT), DType::Int64).unwrap(),
12782 Scalar::Int64(i64::MIN)
12783 );
12784
12785 for target in [DType::Int64Nullable, DType::Float64, DType::Float64Nullable] {
12794 assert!(
12795 cast_scalar(
12796 &Scalar::Datetime64(1_710_498_645_123_456_789),
12797 target.clone()
12798 )
12799 .is_err(),
12800 "datetime64 -> {target:?} must stay refused"
12801 );
12802 assert!(
12803 cast_scalar(&Scalar::Timedelta64(93_784_005_006_007), target.clone()).is_err(),
12804 "timedelta64 -> {target:?} must stay refused"
12805 );
12806 }
12807
12808 for (flag, want) in [(true, 1_i64), (false, 0)] {
12810 assert_eq!(
12811 cast_scalar(&Scalar::Bool(flag), DType::datetime64_naive()).unwrap(),
12812 Scalar::Datetime64(want)
12813 );
12814 assert_eq!(
12815 cast_scalar(&Scalar::Bool(flag), DType::Timedelta64).unwrap(),
12816 Scalar::Timedelta64(want)
12817 );
12818 }
12819 }
12820
12821 #[test]
12825 fn timestamp_string_resolution_and_formatting_match_pandas() {
12826 use super::{DatetimeStringResolution as Res, Timestamp};
12827
12828 const MIDNIGHT: i64 = 1_710_460_800_000_000_000; assert_eq!(Timestamp::string_resolution(MIDNIGHT), Res::Date);
12832 assert_eq!(
12833 Timestamp::string_resolution(MIDNIGHT + 37_845_000_000_000),
12834 Res::Second
12835 );
12836 assert_eq!(
12837 Timestamp::string_resolution(MIDNIGHT + 37_845_123_000_000),
12838 Res::Milli
12839 );
12840 assert_eq!(
12841 Timestamp::string_resolution(MIDNIGHT + 37_845_123_456_000),
12842 Res::Micro
12843 );
12844 assert_eq!(
12845 Timestamp::string_resolution(MIDNIGHT + 37_845_123_456_789),
12846 Res::Nano
12847 );
12848 assert_eq!(
12850 Timestamp::string_resolution(MIDNIGHT + 300_000_000_000),
12851 Res::Second
12852 );
12853 assert_eq!(Timestamp::string_resolution(Timestamp::NAT), Res::Date);
12856
12857 assert!(Res::Date < Res::Second);
12859 assert!(Res::Second < Res::Milli);
12860 assert!(Res::Milli < Res::Micro);
12861 assert!(Res::Micro < Res::Nano);
12862
12863 let value = MIDNIGHT + 37_845_123_456_789;
12865 assert_eq!(
12866 Timestamp::format_at_resolution(value, Res::Date),
12867 "2024-03-15"
12868 );
12869 assert_eq!(
12870 Timestamp::format_at_resolution(value, Res::Second),
12871 "2024-03-15 10:30:45"
12872 );
12873 assert_eq!(
12874 Timestamp::format_at_resolution(value, Res::Milli),
12875 "2024-03-15 10:30:45.123"
12876 );
12877 assert_eq!(
12878 Timestamp::format_at_resolution(value, Res::Micro),
12879 "2024-03-15 10:30:45.123456"
12880 );
12881 assert_eq!(
12882 Timestamp::format_at_resolution(value, Res::Nano),
12883 "2024-03-15 10:30:45.123456789"
12884 );
12885
12886 assert_eq!(
12889 Timestamp::format_at_resolution(MIDNIGHT, Res::Nano),
12890 "2024-03-15 00:00:00.000000000"
12891 );
12892
12893 assert_eq!(
12895 Timestamp::format_at_resolution(MIDNIGHT, Res::Second),
12896 "2024-03-15 00:00:00"
12897 );
12898
12899 for resolution in [Res::Date, Res::Second, Res::Milli, Res::Micro, Res::Nano] {
12901 assert_eq!(
12902 Timestamp::format_at_resolution(Timestamp::NAT, resolution),
12903 "NaT"
12904 );
12905 }
12906
12907 assert_eq!(
12910 Timestamp::format_at_resolution(-1, Res::Nano),
12911 "1969-12-31 23:59:59.999999999"
12912 );
12913
12914 assert_eq!(
12916 Timestamp::format_at_resolution(-9_223_372_036_854_775_806, Res::Nano),
12917 "1677-09-21 00:12:43.145224194"
12918 );
12919 assert_eq!(
12920 Timestamp::format_at_resolution(9_223_372_036_854_775_807, Res::Nano),
12921 "2262-04-11 23:47:16.854775807"
12922 );
12923 }
12924
12925 #[test]
12929 fn cast_scalar_temporal_to_bool_is_nonzero_on_the_nanos() {
12930 use super::{Timedelta, Timestamp, cast_scalar};
12931
12932 for (nanos, want) in [
12934 (0_i64, false),
12935 (1_710_498_645_123_456_789, true),
12936 (-1, true),
12937 (86_400_000_000_000, true),
12938 (1, true),
12939 ] {
12940 assert_eq!(
12941 cast_scalar(&Scalar::Datetime64(nanos), DType::Bool).unwrap(),
12942 Scalar::Bool(want),
12943 "datetime64 {nanos} -> bool"
12944 );
12945 assert_eq!(
12946 cast_scalar(&Scalar::Timedelta64(nanos), DType::Bool).unwrap(),
12947 Scalar::Bool(want),
12948 "timedelta64 {nanos} -> bool"
12949 );
12950 }
12951
12952 assert_eq!(
12956 cast_scalar(&Scalar::Datetime64(Timestamp::NAT), DType::Bool).unwrap(),
12957 Scalar::Bool(true),
12958 "NaT -> bool is true in pandas, not a missing value"
12959 );
12960 assert_eq!(
12961 cast_scalar(&Scalar::Timedelta64(Timedelta::NAT), DType::Bool).unwrap(),
12962 Scalar::Bool(true)
12963 );
12964
12965 for nanos in [0_i64, 1, -1, 1_710_498_645_123_456_789] {
12976 assert!(
12977 cast_scalar(&Scalar::Datetime64(nanos), DType::BoolNullable).is_err(),
12978 "datetime64 {nanos} -> nullable boolean must stay refused"
12979 );
12980 assert!(
12981 cast_scalar(&Scalar::Timedelta64(nanos), DType::BoolNullable).is_err(),
12982 "timedelta64 {nanos} -> nullable boolean must stay refused"
12983 );
12984 }
12985 }
12986
12987 #[test]
12988 fn nancount_nunique_prod_any_all_mx60x() {
12989 use super::{nanall, nanany, nancount, nannunique, nanprod};
12990 let mut s: u64 = 0x4e2a_0b1c_2d3e_4f50;
12993 let mut next = || {
12994 s = s
12995 .wrapping_mul(6_364_136_223_846_793_005)
12996 .wrapping_add(1_442_695_040_888_963_407);
12997 (s >> 33) as u32
12998 };
12999 let asf = |sc: Scalar| -> f64 { sc.to_f64().unwrap_or(f64::NAN) };
13000 let asb = |sc: Scalar| -> bool { matches!(sc, Scalar::Bool(true)) };
13001 for iter in 0..1000u32 {
13002 let n = (next() % 10) as usize + 1;
13003 let raw: Vec<f64> = (0..n)
13004 .map(|_| {
13005 if next() % 4 == 0 {
13006 f64::NAN
13007 } else {
13008 (next() % 5) as f64
13009 }
13010 })
13011 .collect();
13012 let finite: Vec<f64> = raw.iter().copied().filter(|x| !x.is_nan()).collect();
13013 if finite.is_empty() {
13014 continue;
13015 }
13016 let scalars: Vec<Scalar> = raw.iter().map(|&x| Scalar::Float64(x)).collect();
13017 let distinct: std::collections::HashSet<u64> =
13018 finite.iter().map(|x| x.to_bits()).collect();
13019 let prod: f64 = finite.iter().product();
13020 assert!(
13021 (asf(nancount(&scalars)) - finite.len() as f64).abs() < 1e-9,
13022 "nancount iter={iter}"
13023 );
13024 assert!(
13025 (asf(nannunique(&scalars)) - distinct.len() as f64).abs() < 1e-9,
13026 "nannunique iter={iter}"
13027 );
13028 assert!(
13029 (asf(nanprod(&scalars)) - prod).abs() < 1e-7,
13030 "nanprod iter={iter}"
13031 );
13032 assert_eq!(
13033 asb(nanany(&scalars)),
13034 finite.iter().any(|&x| x != 0.0),
13035 "nanany iter={iter}"
13036 );
13037 assert_eq!(
13038 asb(nanall(&scalars)),
13039 finite.iter().all(|&x| x != 0.0),
13040 "nanall iter={iter}"
13041 );
13042 }
13043 }
13044
13045 #[test]
13046 fn nan_reduction_kernels_skip_correctness_1uagc() {
13047 use super::{nanmax, nanmedian, nanmin, nansum};
13048 let mut s: u64 = 0x4e1a_0b2c_2d3e_4f50;
13051 let mut next = || {
13052 s = s
13053 .wrapping_mul(6_364_136_223_846_793_005)
13054 .wrapping_add(1_442_695_040_888_963_407);
13055 (s >> 33) as u32
13056 };
13057 let val = |sc: Scalar| -> f64 { sc.to_f64().unwrap_or(f64::NAN) };
13058 for iter in 0..1000u32 {
13059 let n = (next() % 12) as usize + 1;
13060 let raw: Vec<f64> = (0..n)
13061 .map(|_| {
13062 if next() % 4 == 0 {
13063 f64::NAN
13064 } else {
13065 (next() % 200) as f64 - 100.0
13066 }
13067 })
13068 .collect();
13069 let mut finite: Vec<f64> = raw.iter().copied().filter(|x| !x.is_nan()).collect();
13070 if finite.is_empty() {
13071 continue;
13072 }
13073 let scalars: Vec<Scalar> = raw.iter().map(|&x| Scalar::Float64(x)).collect();
13074 let sum: f64 = finite.iter().sum();
13075 let mn = finite.iter().copied().fold(f64::INFINITY, f64::min);
13076 let mx = finite.iter().copied().fold(f64::NEG_INFINITY, f64::max);
13077 finite.sort_by(|a, b| a.partial_cmp(b).unwrap());
13078 let m = finite.len();
13079 let med = if m % 2 == 1 {
13080 finite[m / 2]
13081 } else {
13082 (finite[m / 2 - 1] + finite[m / 2]) / 2.0
13083 };
13084 assert!(
13085 (val(nansum(&scalars)) - sum).abs() < 1e-7,
13086 "nansum iter={iter}"
13087 );
13088 assert!(
13089 (val(nanmin(&scalars)) - mn).abs() < 1e-9,
13090 "nanmin iter={iter}"
13091 );
13092 assert!(
13093 (val(nanmax(&scalars)) - mx).abs() < 1e-9,
13094 "nanmax iter={iter}"
13095 );
13096 assert!(
13097 (val(nanmedian(&scalars)) - med).abs() < 1e-9,
13098 "nanmedian iter={iter}"
13099 );
13100 }
13101 }
13102
13103 #[test]
13104 fn nanvar_ddof_nanstd_nan_skip_p00ag() {
13105 use super::{nanmean, nanstd, nanvar};
13106 let mut s: u64 = 0x4e0a_0b1c_2d3e_4f50;
13109 let mut next = || {
13110 s = s
13111 .wrapping_mul(6_364_136_223_846_793_005)
13112 .wrapping_add(1_442_695_040_888_963_407);
13113 (s >> 33) as u32
13114 };
13115 let val = |sc: Scalar| -> f64 { sc.to_f64().unwrap_or(f64::NAN) };
13116 for iter in 0..1000u32 {
13117 let n = (next() % 10) as usize + 2;
13118 let raw: Vec<f64> = (0..n)
13119 .map(|_| {
13120 if next() % 4 == 0 {
13121 f64::NAN
13122 } else {
13123 (next() % 200) as f64 / 7.0
13124 }
13125 })
13126 .collect();
13127 let finite: Vec<f64> = raw.iter().copied().filter(|x| !x.is_nan()).collect();
13128 if finite.len() < 2 {
13129 continue;
13130 }
13131 let scalars: Vec<Scalar> = raw.iter().map(|&x| Scalar::Float64(x)).collect();
13132 let nf = finite.len() as f64;
13133 let mean = finite.iter().sum::<f64>() / nf;
13134 let ss = finite.iter().map(|x| (x - mean).powi(2)).sum::<f64>();
13135 assert!(
13136 (val(nanmean(&scalars)) - mean).abs() < 1e-7,
13137 "nanmean iter={iter}"
13138 );
13139 assert!(
13140 (val(nanvar(&scalars, 0)) - ss / nf).abs() < 1e-7,
13141 "nanvar ddof0 iter={iter}"
13142 );
13143 assert!(
13144 (val(nanvar(&scalars, 1)) - ss / (nf - 1.0)).abs() < 1e-7,
13145 "nanvar ddof1 iter={iter}"
13146 );
13147 assert!(
13148 (val(nanstd(&scalars, 1)) - (ss / (nf - 1.0)).sqrt()).abs() < 1e-7,
13149 "nanstd ddof1 iter={iter}"
13150 );
13151 }
13152 }
13153
13154 #[test]
13155 fn nanskew_nankurt_min_sample_and_known_xybnq() {
13156 use super::{nankurt, nanskew};
13159 let f = |xs: &[f64]| -> Vec<Scalar> { xs.iter().map(|&x| Scalar::Float64(x)).collect() };
13160 let val = |s: Scalar| -> Option<f64> {
13161 if s.is_missing() {
13162 None
13163 } else {
13164 s.to_f64().ok()
13165 }
13166 };
13167
13168 assert_eq!(val(nanskew(&f(&[1.0, 2.0]))), None, "skew n=2 -> NaN");
13170 let sym = val(nanskew(&f(&[1.0, 2.0, 3.0]))).expect("skew n=3");
13171 assert!(sym.abs() < 1e-9, "symmetric skew ~0, got {sym}");
13172 let right = val(nanskew(&f(&[1.0, 1.0, 1.0, 5.0]))).expect("skew n=4");
13173 assert!(right > 0.0, "right-skewed -> positive skew, got {right}");
13174
13175 assert_eq!(val(nankurt(&f(&[1.0, 2.0, 3.0]))), None, "kurt n=3 -> NaN");
13177 let k = val(nankurt(&f(&[1.0, 2.0, 3.0, 4.0, 5.0]))).expect("kurt n=5");
13178 assert!(
13179 (k - (-1.2)).abs() < 1e-6,
13180 "pandas kurt([1..5]) == -1.2, got {k}"
13181 );
13182 }
13183
13184 #[test]
13185 #[ignore = "foreground release attribution harness"]
13186 fn nanskew_fused_moment_scan_ab_mavln() {
13187 const ROWS: usize = 100_000;
13188 const BATCH: usize = 8;
13189
13190 fn former(values: &[Scalar]) -> Scalar {
13191 let nums = super::collect_finite(values);
13192 let n = nums.len() as f64;
13193 if n < 3.0 {
13194 return Scalar::Null(NullKind::NaN);
13195 }
13196 let mean = nums.iter().sum::<f64>() / n;
13197 let m2: f64 = nums.iter().map(|x| (x - mean).powi(2)).sum();
13198 let m3: f64 = nums.iter().map(|x| (x - mean).powi(3)).sum();
13199 let s2 = m2 / (n - 1.0);
13200 if s2 == 0.0 {
13201 return Scalar::Float64(0.0);
13202 }
13203 let s3 = s2.powf(1.5);
13204 Scalar::Float64((n / ((n - 1.0) * (n - 2.0))) * (m3 / s3))
13205 }
13206
13207 fn assert_bits_eq(former: Scalar, candidate: Scalar) {
13208 match (former, candidate) {
13209 (Scalar::Float64(a), Scalar::Float64(b)) => assert_eq!(a.to_bits(), b.to_bits()),
13210 (a, b) => assert_eq!(a, b),
13211 }
13212 }
13213
13214 fn elapsed(values: &[Scalar], skew: fn(&[Scalar]) -> Scalar) -> u128 {
13215 std::hint::black_box(skew(std::hint::black_box(values)));
13216 let started = std::time::Instant::now();
13217 for _ in 0..BATCH {
13218 std::hint::black_box(skew(std::hint::black_box(values)));
13219 }
13220 started.elapsed().as_nanos()
13221 }
13222
13223 fn median(samples: &mut [u128]) -> u128 {
13224 samples.sort_unstable();
13225 samples[samples.len() / 2]
13226 }
13227
13228 for values in [
13229 vec![],
13230 vec![Scalar::Int64(1), Scalar::Int64(2)],
13231 vec![Scalar::Int64(7); 16],
13232 vec![
13233 Scalar::Int64(-3),
13234 Scalar::Null(NullKind::NaN),
13235 Scalar::Float64(2.5),
13236 Scalar::Utf8("skip".to_owned()),
13237 Scalar::Int64(11),
13238 ],
13239 ] {
13240 assert_bits_eq(former(&values), super::nanskew(&values));
13241 }
13242
13243 let values = (0..ROWS)
13244 .map(|i| {
13245 if i % 257 == 0 {
13246 Scalar::Null(NullKind::NaN)
13247 } else {
13248 Scalar::Int64(((i * 37 + i / 11) % 10_003) as i64 - 5_001)
13249 }
13250 })
13251 .collect::<Vec<_>>();
13252 assert_bits_eq(former(&values), super::nanskew(&values));
13253
13254 for _ in 0..2 {
13255 std::hint::black_box(elapsed(&values, former));
13256 std::hint::black_box(elapsed(&values, super::nanskew));
13257 }
13258
13259 let mut former_samples = Vec::with_capacity(18);
13260 let mut candidate_samples = Vec::with_capacity(18);
13261 for block in 0_usize..9 {
13262 if block.is_multiple_of(2) {
13263 former_samples.push(elapsed(&values, former));
13264 candidate_samples.push(elapsed(&values, super::nanskew));
13265 candidate_samples.push(elapsed(&values, super::nanskew));
13266 former_samples.push(elapsed(&values, former));
13267 } else {
13268 candidate_samples.push(elapsed(&values, super::nanskew));
13269 former_samples.push(elapsed(&values, former));
13270 former_samples.push(elapsed(&values, former));
13271 candidate_samples.push(elapsed(&values, super::nanskew));
13272 }
13273 }
13274
13275 let former_p50 = median(&mut former_samples);
13276 let candidate_p50 = median(&mut candidate_samples);
13277 eprintln!(
13278 "NANSKEW_FUSED_AB rows={ROWS} batch={BATCH} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} ratio={:.6}",
13279 former_p50 as f64 / candidate_p50 as f64,
13280 );
13281 eprintln!("NANSKEW_FUSED_AB former_samples_ns={former_samples:?}");
13282 eprintln!("NANSKEW_FUSED_AB candidate_samples_ns={candidate_samples:?}");
13283 }
13284
13285 #[test]
13286 #[ignore = "foreground performance probe"]
13287 fn nankurt_fused_moment_scan_ab_idka7() {
13288 const ROWS: usize = 65_536;
13289 const BATCH: usize = 4;
13290
13291 fn former(values: &[Scalar]) -> Scalar {
13292 let nums = super::collect_finite(values);
13293 let n = nums.len() as f64;
13294 if n < 4.0 {
13295 return Scalar::Null(NullKind::NaN);
13296 }
13297 let mean = nums.iter().sum::<f64>() / n;
13298 let m2: f64 = nums.iter().map(|x| (x - mean).powi(2)).sum();
13299 let m4: f64 = nums.iter().map(|x| (x - mean).powi(4)).sum();
13300 let s2 = m2 / (n - 1.0);
13301 if s2 == 0.0 {
13302 return Scalar::Float64(0.0);
13303 }
13304 let adj = (n * (n + 1.0)) / ((n - 1.0) * (n - 2.0) * (n - 3.0));
13305 let sub = (3.0 * (n - 1.0).powi(2)) / ((n - 2.0) * (n - 3.0));
13306 Scalar::Float64(adj * (m4 / (s2 * s2)) - sub)
13307 }
13308
13309 fn assert_bits_eq(former: Scalar, candidate: Scalar) {
13310 match (former, candidate) {
13311 (Scalar::Float64(a), Scalar::Float64(b)) => assert_eq!(a.to_bits(), b.to_bits()),
13312 (a, b) => assert_eq!(a, b),
13313 }
13314 }
13315
13316 fn elapsed(values: &[Scalar], kurt: fn(&[Scalar]) -> Scalar) -> u128 {
13317 let started = std::time::Instant::now();
13318 for _ in 0..BATCH {
13319 std::hint::black_box(kurt(std::hint::black_box(values)));
13320 }
13321 started.elapsed().as_nanos()
13322 }
13323
13324 fn median(samples: &mut [u128]) -> u128 {
13325 samples.sort_unstable();
13326 samples[samples.len() / 2]
13327 }
13328
13329 for values in [
13330 vec![],
13331 vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
13332 vec![Scalar::Int64(7); 16],
13333 vec![
13334 Scalar::Int64(-3),
13335 Scalar::Null(NullKind::NaN),
13336 Scalar::Float64(2.5),
13337 Scalar::Utf8("skip".to_owned()),
13338 Scalar::Int64(11),
13339 Scalar::Float64(-7.25),
13340 ],
13341 ] {
13342 assert_bits_eq(former(&values), super::nankurt(&values));
13343 }
13344
13345 let values = (0..ROWS)
13346 .map(|i| {
13347 if i % 257 == 0 {
13348 Scalar::Null(NullKind::NaN)
13349 } else {
13350 Scalar::Int64(((i * 37 + i / 11) % 10_003) as i64 - 5_001)
13351 }
13352 })
13353 .collect::<Vec<_>>();
13354 assert_bits_eq(former(&values), super::nankurt(&values));
13355
13356 for _ in 0..2 {
13357 std::hint::black_box(elapsed(&values, former));
13358 std::hint::black_box(elapsed(&values, super::nankurt));
13359 }
13360
13361 let mut former_samples = Vec::with_capacity(10);
13362 let mut candidate_samples = Vec::with_capacity(10);
13363 for block in 0_usize..5 {
13364 if block.is_multiple_of(2) {
13365 former_samples.push(elapsed(&values, former));
13366 candidate_samples.push(elapsed(&values, super::nankurt));
13367 candidate_samples.push(elapsed(&values, super::nankurt));
13368 former_samples.push(elapsed(&values, former));
13369 } else {
13370 candidate_samples.push(elapsed(&values, super::nankurt));
13371 former_samples.push(elapsed(&values, former));
13372 former_samples.push(elapsed(&values, former));
13373 candidate_samples.push(elapsed(&values, super::nankurt));
13374 }
13375 }
13376
13377 let former_p50 = median(&mut former_samples);
13378 let candidate_p50 = median(&mut candidate_samples);
13379 eprintln!(
13380 "NANKURT_FUSED_AB rows={ROWS} batch={BATCH} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} ratio={:.6}",
13381 former_p50 as f64 / candidate_p50 as f64,
13382 );
13383 eprintln!("NANKURT_FUSED_AB former_samples_ns={former_samples:?}");
13384 eprintln!("NANKURT_FUSED_AB candidate_samples_ns={candidate_samples:?}");
13385 }
13386
13387 #[test]
13390 fn cast_scalar_to_utf8_formatting_yes7i() {
13391 let mut st: u64 = 0x4e57_0b1c_2d3e_4f50;
13394 let mut next = || {
13395 st = st
13396 .wrapping_mul(6_364_136_223_846_793_005)
13397 .wrapping_add(1_442_695_040_888_963_407);
13398 (st >> 33) as u32
13399 };
13400 for _ in 0..3000u32 {
13401 let n = (next() % 4_000_001) as i64 - 2_000_000;
13402 assert_eq!(
13403 cast_scalar(&Scalar::Int64(n), DType::Utf8).unwrap(),
13404 Scalar::Utf8(n.to_string())
13405 );
13406 }
13407 assert_eq!(
13408 cast_scalar(&Scalar::Bool(true), DType::Utf8).unwrap(),
13409 Scalar::Utf8("True".to_string())
13410 );
13411 assert_eq!(
13412 cast_scalar(&Scalar::Bool(false), DType::Utf8).unwrap(),
13413 Scalar::Utf8("False".to_string())
13414 );
13415 }
13416
13417 #[test]
13418 fn cast_scalar_coercion_rules_6a83t() {
13419 let mut state: u64 = 0x5a17_c0de_1234_abcd;
13420 let mut next = || {
13421 state = state
13422 .wrapping_mul(6_364_136_223_846_793_005)
13423 .wrapping_add(1_442_695_040_888_963_407);
13424 (state >> 33) as u32
13425 };
13426
13427 for _ in 0..4000u32 {
13428 let n = (next() % 21) as i64 - 10; let b = next() % 2 == 0;
13430 let f = f64::from((next() % 41) as i32 - 20) / 4.0; let i = Scalar::Int64(n);
13433 let bo = Scalar::Bool(b);
13434 let fl = Scalar::Float64(f);
13435
13436 assert_eq!(cast_scalar(&i, DType::Int64), Ok(i.clone()));
13438 assert_eq!(cast_scalar(&bo, DType::Bool), Ok(bo.clone()));
13439 assert_eq!(cast_scalar(&fl, DType::Float64), Ok(fl.clone()));
13440
13441 assert_eq!(cast_scalar(&i, DType::Int64Nullable), Ok(i.clone()));
13443 assert_eq!(cast_scalar(&bo, DType::BoolNullable), Ok(bo.clone()));
13444
13445 assert_eq!(cast_scalar(&i, DType::Bool), Ok(Scalar::Bool(n != 0)));
13447 assert_eq!(
13448 cast_scalar(&i, DType::Float64),
13449 Ok(Scalar::Float64(n as f64))
13450 );
13451
13452 assert_eq!(
13454 cast_scalar(&bo, DType::Int64),
13455 Ok(Scalar::Int64(i64::from(b)))
13456 );
13457 assert_eq!(
13458 cast_scalar(&bo, DType::Float64),
13459 Ok(Scalar::Float64(if b { 1.0 } else { 0.0 }))
13460 );
13461
13462 assert_eq!(cast_scalar(&fl, DType::Int64), Ok(Scalar::Int64(f as i64)));
13464 }
13465 }
13466
13467 #[test]
13469 fn scalar_from_primitive_types() {
13470 assert_eq!(Scalar::from(true), Scalar::Bool(true));
13472 assert_eq!(Scalar::from(42i64), Scalar::Int64(42));
13473 assert_eq!(Scalar::from(1.5f64), Scalar::Float64(1.5));
13474 assert_eq!(Scalar::from("hi"), Scalar::Utf8("hi".to_owned()));
13475 assert_eq!(
13476 Scalar::from(String::from("world")),
13477 Scalar::Utf8("world".to_owned())
13478 );
13479
13480 let mixed: Vec<Scalar> = vec![1i64.into(), 2.0f64.into(), "three".into()];
13484 assert_eq!(mixed[0], Scalar::Int64(1));
13485 assert_eq!(mixed[1], Scalar::Float64(2.0));
13486 assert_eq!(mixed[2], Scalar::Utf8("three".to_owned()));
13487 }
13488
13489 #[test]
13490 fn dtype_inference_routes_bool_numeric_mix_to_object_bucket_rh1od() {
13491 let values = vec![Scalar::Bool(true), Scalar::Int64(7), Scalar::Float64(3.5)];
13496 assert_eq!(
13497 infer_dtype(&values).expect("dtype should infer"),
13498 DType::Utf8
13499 );
13500 }
13501
13502 #[test]
13503 fn interval_scalar_has_dtype_storage_and_unique_semantics_5g5uj() {
13504 let left = Scalar::Interval(Interval::new(0.0, 1.0, IntervalClosed::Right));
13505 let right = Scalar::Interval(Interval::new(1.0, 2.0, IntervalClosed::Right));
13506 assert_eq!(left.dtype(), DType::Interval);
13507 assert!(!left.is_missing());
13508 assert_eq!(
13509 infer_dtype(&[left.clone(), right.clone()]).expect("interval dtype"),
13510 DType::Interval
13511 );
13512 assert_eq!(
13513 common_dtype(DType::Interval, DType::Interval).expect("same interval dtype"),
13514 DType::Interval
13515 );
13516 assert_eq!(
13517 cast_scalar(&Scalar::Null(NullKind::Null), DType::Interval).expect("missing casts"),
13518 Scalar::Null(NullKind::Null)
13519 );
13520 assert_eq!(
13521 cast_scalar(&left, DType::Utf8).expect("interval string cast"),
13522 Scalar::Utf8("(0.0, 1.0]".to_owned())
13523 );
13524 assert_eq!(
13525 super::nannunique(&[left.clone(), right, left, Scalar::Null(NullKind::Null)]),
13526 Scalar::Int64(2)
13527 );
13528 }
13529
13530 #[test]
13531 fn cast_scalar_parses_temporal_extension_strings_avm08() {
13532 let expected_nanos = super::Timestamp::parse("2024-01-15T10:30:45")
13533 .expect("timestamp parse")
13534 .nanos;
13535 assert_eq!(
13536 cast_scalar(
13537 &Scalar::Utf8("2024-01-15T10:30:45".to_owned()),
13538 DType::datetime64_naive()
13539 )
13540 .expect("datetime cast"),
13541 Scalar::Datetime64(expected_nanos)
13542 );
13543 assert_eq!(
13544 cast_scalar(&Scalar::Utf8("2024Q1".to_owned()), DType::Period).expect("period cast"),
13545 Scalar::Period(Period::new(216, PeriodFreq::QUARTERLY))
13546 );
13547 assert_eq!(
13548 cast_scalar(&Scalar::Utf8("(0, 1]".to_owned()), DType::Interval)
13549 .expect("interval cast"),
13550 Scalar::Interval(Interval::new(0.0, 1.0, IntervalClosed::Right))
13551 );
13552 }
13553
13554 #[test]
13555 fn missing_values_get_target_missing_marker() {
13556 let missing = Scalar::Null(NullKind::Null);
13557 let cast = cast_scalar(&missing, DType::Float64).expect("missing casts");
13558 assert_eq!(cast, Scalar::Null(NullKind::NaN));
13559 }
13560
13561 #[test]
13562 fn cast_scalar_to_utf8_uses_pandas_string_spellings() {
13563 let cases = [
13564 (Scalar::Bool(true), "True"),
13565 (Scalar::Bool(false), "False"),
13566 (Scalar::Int64(-7), "-7"),
13567 (Scalar::Float64(1.0), "1.0"),
13568 (Scalar::Float64(1.5), "1.5"),
13569 (Scalar::Float64(f64::NAN), "nan"),
13570 (Scalar::Null(NullKind::Null), "None"),
13571 (Scalar::Null(NullKind::NaN), "nan"),
13572 (Scalar::Null(NullKind::NaT), "NaT"),
13573 ];
13574
13575 for (value, expected) in cases {
13576 assert_eq!(
13577 cast_scalar(&value, DType::Utf8).expect("cast"),
13578 Scalar::Utf8(expected.to_owned())
13579 );
13580 }
13581 }
13582
13583 #[test]
13584 fn semantic_eq_treats_nan_as_equal() {
13585 let left = Scalar::Float64(f64::NAN);
13586 let right = Scalar::Null(NullKind::NaN);
13587 assert!(left.semantic_eq(&right));
13588 }
13589
13590 #[test]
13591 fn semantic_eq_treats_nan_as_missing_null() {
13592 let left = Scalar::Float64(f64::NAN);
13593 let right = Scalar::Null(NullKind::Null);
13594 assert!(left.semantic_eq(&right));
13595 }
13596
13597 #[test]
13616 fn semantic_eq_unifies_dtype_sentinel_missing_with_null_xwxci() {
13617 for sentinel in [
13618 Scalar::Timedelta64(Timedelta::NAT),
13619 Scalar::Datetime64(Timestamp::NAT),
13620 Scalar::Period(Period::new(i64::MIN, PeriodFreq::Daily)),
13621 ] {
13622 assert!(sentinel.is_missing(), "{sentinel:?} must report missing");
13623 for marker in [
13624 Scalar::Null(NullKind::Null),
13625 Scalar::Null(NullKind::NaN),
13626 Scalar::Null(NullKind::NaT),
13627 ] {
13628 assert!(
13629 sentinel.semantic_eq(&marker),
13630 "{sentinel:?} vs {marker:?} are both missing"
13631 );
13632 assert!(marker.semantic_eq(&sentinel), "and symmetrically");
13633 }
13634 }
13635
13636 let present = Scalar::Timedelta64(-60);
13638 assert!(!Scalar::Timedelta64(Timedelta::NAT).semantic_eq(&present));
13639 assert!(!present.semantic_eq(&Scalar::Null(NullKind::Null)));
13640 assert!(!present.semantic_eq(&Scalar::Timedelta64(-61)));
13642 }
13643
13644 #[test]
13645 fn common_dtype_rejects_string_numeric_mix() {
13646 let err = common_dtype(DType::Utf8, DType::Int64).expect_err("must fail");
13647 assert_eq!(
13648 err.to_string(),
13649 "dtype coercion from Utf8 to Int64 has no compatible common type"
13650 );
13651 let err = common_dtype(DType::Float64, DType::Utf8).expect_err("must fail");
13652 assert_eq!(
13653 err.to_string(),
13654 "dtype coercion from Float64 to Utf8 has no compatible common type"
13655 );
13656 }
13657
13658 #[test]
13659 fn sparse_dtype_normalizes_fill_value_to_value_dtype() {
13660 let dtype = SparseDType::new(DType::Float64, Scalar::Int64(0)).expect("fill should cast");
13661
13662 assert_eq!(dtype.value_dtype, DType::Float64);
13663 assert_eq!(dtype.fill_value, Scalar::Float64(0.0));
13664 }
13665
13666 #[test]
13667 fn sparse_dtype_rejects_sparse_value_dtype() {
13668 let err = SparseDType::new(DType::Sparse, Scalar::Int64(0)).expect_err("must reject");
13669
13670 assert_eq!(err.to_string(), "sparse value dtype cannot be Sparse");
13671 }
13672
13673 #[test]
13674 fn common_dtype_rejects_sparse_dense_mix() {
13675 let err = common_dtype(DType::Sparse, DType::Int64).expect_err("must fail");
13676
13677 assert_eq!(
13678 err.to_string(),
13679 "dtype coercion from Sparse to Int64 has no compatible common type"
13680 );
13681 }
13682
13683 #[test]
13686 fn nullable_int64_promotion_matrix() {
13687 assert_eq!(
13689 common_dtype(DType::Int64, DType::Int64Nullable).unwrap(),
13690 DType::Int64Nullable
13691 );
13692 assert_eq!(
13693 common_dtype(DType::Int64Nullable, DType::Int64).unwrap(),
13694 DType::Int64Nullable
13695 );
13696
13697 assert_eq!(
13704 common_dtype(DType::Int64Nullable, DType::Float64).unwrap(),
13705 DType::Float64Nullable
13706 );
13707 assert_eq!(
13708 common_dtype(DType::Float64, DType::Int64Nullable).unwrap(),
13709 DType::Float64Nullable
13710 );
13711
13712 assert_eq!(
13714 common_dtype(DType::Int64Nullable, DType::Int64Nullable).unwrap(),
13715 DType::Int64Nullable
13716 );
13717
13718 assert_eq!(
13720 common_dtype(DType::Bool, DType::Int64Nullable).unwrap(),
13721 DType::Int64Nullable
13722 );
13723
13724 assert_eq!(
13726 common_dtype(DType::BoolNullable, DType::Int64).unwrap(),
13727 DType::Int64Nullable
13728 );
13729 }
13730
13731 #[test]
13732 fn nullable_bool_promotion_matrix() {
13733 assert_eq!(
13735 common_dtype(DType::Bool, DType::BoolNullable).unwrap(),
13736 DType::BoolNullable
13737 );
13738 assert_eq!(
13739 common_dtype(DType::BoolNullable, DType::Bool).unwrap(),
13740 DType::BoolNullable
13741 );
13742
13743 assert_eq!(
13750 common_dtype(DType::BoolNullable, DType::Float64).unwrap(),
13751 DType::Float64Nullable
13752 );
13753
13754 assert_eq!(
13757 common_dtype(DType::Bool, DType::Float64).unwrap(),
13758 DType::Float64
13759 );
13760 }
13761
13762 #[test]
13763 fn dtype_is_nullable_helper() {
13764 assert!(DType::Int64Nullable.is_nullable());
13765 assert!(DType::BoolNullable.is_nullable());
13766 assert!(!DType::Int64.is_nullable());
13767 assert!(!DType::Bool.is_nullable());
13768 assert!(!DType::Float64.is_nullable());
13769 assert!(!DType::Utf8.is_nullable());
13770 }
13771
13772 #[test]
13773 fn dtype_to_nullable_conversions() {
13774 assert_eq!(DType::Int64.to_nullable(), DType::Int64Nullable);
13775 assert_eq!(DType::Bool.to_nullable(), DType::BoolNullable);
13776 assert_eq!(DType::Float64.to_nullable(), DType::Float64Nullable);
13786 assert_eq!(
13787 DType::Float64Nullable.to_nullable(),
13788 DType::Float64Nullable,
13789 "idempotent: already nullable"
13790 );
13791 assert_eq!(DType::Int64Nullable.to_nullable(), DType::Int64Nullable);
13792 }
13793
13794 #[test]
13795 fn dtype_to_non_nullable_conversions() {
13796 assert_eq!(DType::Int64Nullable.to_non_nullable(), DType::Int64);
13797 assert_eq!(DType::BoolNullable.to_non_nullable(), DType::Bool);
13798 assert_eq!(DType::Int64.to_non_nullable(), DType::Int64); assert_eq!(DType::Float64.to_non_nullable(), DType::Float64);
13800 }
13801
13802 #[test]
13803 fn nullable_dtype_name_reports_pandas_style() {
13804 assert_eq!(DType::Int64.name(), "int64");
13805 assert_eq!(DType::Int64Nullable.name(), "Int64"); assert_eq!(DType::Bool.name(), "bool");
13807 assert_eq!(DType::BoolNullable.name(), "boolean");
13808 }
13809
13810 #[test]
13811 fn cast_scalar_int64_nullable_identity() {
13812 let val = Scalar::Int64(42);
13813 let result = cast_scalar(&val, DType::Int64Nullable).unwrap();
13815 assert_eq!(result, Scalar::Int64(42));
13816
13817 let result2 = cast_scalar(&val, DType::Int64).unwrap();
13819 assert_eq!(result2, Scalar::Int64(42));
13820 }
13821
13822 #[test]
13823 fn cast_float_to_utf8_uses_pandas_str_float_with_scientific() {
13824 let cases: &[(f64, &str)] = &[
13829 (1.0, "1.0"),
13830 (2.5, "2.5"),
13831 (100.0, "100.0"),
13832 (0.1, "0.1"),
13833 (0.0001, "0.0001"),
13834 (1e16, "1e+16"),
13835 (1e20, "1e+20"),
13836 (1e-5, "1e-05"),
13837 (1e-7, "1e-07"),
13838 (f64::INFINITY, "inf"),
13839 (f64::NEG_INFINITY, "-inf"),
13840 ];
13841 for (v, expected) in cases {
13842 assert_eq!(
13843 cast_scalar(&Scalar::Float64(*v), DType::Utf8).unwrap(),
13844 Scalar::Utf8((*expected).to_owned()),
13845 "float {v} -> str"
13846 );
13847 }
13848 }
13849
13850 fn float_to_string_for_astype_former(value: f64) -> String {
13851 if value.is_nan() {
13852 return "nan".to_owned();
13853 }
13854 if value.is_infinite() {
13855 return value.to_string();
13856 }
13857 let rendered = format!("{value:?}");
13858 match rendered.split_once('e') {
13859 None => rendered,
13860 Some((mantissa, exponent)) => {
13861 let (sign, digits) = match exponent.strip_prefix('-') {
13862 Some(digits) => ('-', digits),
13863 None => ('+', exponent.strip_prefix('+').unwrap_or(exponent)),
13864 };
13865 format!("{mantissa}e{sign}{digits:0>2}")
13866 }
13867 }
13868 }
13869
13870 fn scientific_astype_values(len: usize) -> Vec<f64> {
13871 const EXPONENTS: [i32; 16] = [
13872 -300, -200, -100, -50, -10, -7, -6, -5, 16, 17, 20, 50, 100, 200, 300, 307,
13873 ];
13874 (0..len)
13875 .map(|position| {
13876 let mantissa = 1.0 + (position % 997) as f64 / 997.0;
13877 let magnitude = mantissa * 10.0_f64.powi(EXPONENTS[position % EXPONENTS.len()]);
13878 if position.is_multiple_of(2) {
13879 magnitude
13880 } else {
13881 -magnitude
13882 }
13883 })
13884 .collect()
13885 }
13886
13887 #[test]
13888 fn float_to_string_for_astype_in_place_matches_former() {
13889 let fixed = [
13890 f64::NAN,
13891 f64::INFINITY,
13892 f64::NEG_INFINITY,
13893 0.0,
13894 -0.0,
13895 f64::MIN_POSITIVE,
13896 f64::MAX,
13897 f64::MIN,
13898 1e16,
13899 -1e16,
13900 1e-5,
13901 -1e-5,
13902 1.234_567_890_123_456_8e20,
13903 -9.876_543_210_987_654e-123,
13904 ];
13905 for value in fixed.into_iter().chain(scientific_astype_values(16_384)) {
13906 assert_eq!(
13907 super::float_to_string_for_astype(value),
13908 float_to_string_for_astype_former(value),
13909 "value={value:?}"
13910 );
13911 }
13912 }
13913
13914 #[test]
13915 #[ignore = "foreground performance probe"]
13916 fn float_to_string_for_astype_in_place_ab() {
13917 use std::time::Instant;
13918
13919 const VALUES: usize = 16_384;
13920 const SAMPLES: usize = 10;
13921 let values = scientific_astype_values(VALUES);
13922 for &value in &values {
13923 let former = float_to_string_for_astype_former(value);
13924 assert!(former.contains('e'), "benchmark value must be scientific");
13925 assert_eq!(super::float_to_string_for_astype(value), former);
13926 }
13927
13928 for _ in 0..2 {
13929 for &value in &values {
13930 std::hint::black_box(float_to_string_for_astype_former(value));
13931 std::hint::black_box(super::float_to_string_for_astype(value));
13932 }
13933 }
13934
13935 let mut former_ns = Vec::with_capacity(SAMPLES);
13936 let mut public_ns = Vec::with_capacity(SAMPLES);
13937 for sample in 0..SAMPLES {
13938 let run = |formatter: fn(f64) -> String| {
13939 let started = Instant::now();
13940 for &value in std::hint::black_box(&values) {
13941 std::hint::black_box(formatter(std::hint::black_box(value)));
13942 }
13943 started.elapsed().as_nanos()
13944 };
13945 if sample.is_multiple_of(2) {
13946 former_ns.push(run(float_to_string_for_astype_former));
13947 public_ns.push(run(super::float_to_string_for_astype));
13948 } else {
13949 public_ns.push(run(super::float_to_string_for_astype));
13950 former_ns.push(run(float_to_string_for_astype_former));
13951 }
13952 }
13953
13954 former_ns.sort_unstable();
13955 public_ns.sort_unstable();
13956 let former_p50 = former_ns[SAMPLES / 2];
13957 let public_p50 = public_ns[SAMPLES / 2];
13958 println!(
13959 "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:?}",
13960 former_p50 as f64 / public_p50 as f64
13961 );
13962 }
13963
13964 #[test]
13965 fn cast_float_to_utf8_threshold_boundaries_match_python() {
13966 let cases: &[(f64, &str)] = &[
13971 (1e15, "1000000000000000.0"),
13972 (9_999_999_999_999_998.0, "9999999999999998.0"),
13973 (1_234_567_890_123_456.0, "1234567890123456.0"),
13974 (123_456_789_012_345.0, "123456789012345.0"),
13975 (12_345_678_901_234_567.0, "1.2345678901234568e+16"),
13976 (1e16, "1e+16"),
13977 (1.5e16, "1.5e+16"),
13978 (1e17, "1e+17"),
13979 (1e-4, "0.0001"),
13980 (5e-5, "5e-05"),
13981 (-1e15, "-1000000000000000.0"),
13982 (-1e16, "-1e+16"),
13983 (-1e-5, "-1e-05"),
13984 ];
13985 for (v, expected) in cases {
13986 assert_eq!(
13987 cast_scalar(&Scalar::Float64(*v), DType::Utf8).unwrap(),
13988 Scalar::Utf8((*expected).to_owned()),
13989 "float {v} -> str"
13990 );
13991 }
13992 }
13993
13994 #[test]
13995 fn cast_to_bool_uses_pandas_nonzero_truthiness() {
13996 let cases_int: &[(i64, bool)] = &[(0, false), (1, true), (-3, true), (2, true)];
14000 for (v, expected) in cases_int {
14001 assert_eq!(
14002 cast_scalar(&Scalar::Int64(*v), DType::Bool).unwrap(),
14003 Scalar::Bool(*expected),
14004 "int {v} -> bool"
14005 );
14006 }
14007 let cases_float: &[(f64, bool)] = &[
14008 (0.0, false),
14009 (-0.0, false),
14010 (0.1, true),
14011 (2.5, true),
14012 (1.0, true),
14013 (f64::NAN, true),
14015 ];
14016 for (v, expected) in cases_float {
14017 assert_eq!(
14018 cast_scalar(&Scalar::Float64(*v), DType::Bool).unwrap(),
14019 Scalar::Bool(*expected),
14020 "float {v} -> bool"
14021 );
14022 }
14023 }
14024
14025 #[test]
14026 fn nullable_dtype_is_extension() {
14027 assert!(DType::Int64Nullable.is_extension());
14028 assert!(DType::BoolNullable.is_extension());
14029 assert!(!DType::Int64.is_extension());
14030 assert!(!DType::Bool.is_extension());
14031 }
14032
14033 #[test]
14034 fn infer_dtype_preserves_string_numeric_mix_as_utf8_bucket() {
14035 let values = vec![Scalar::Utf8("x".into()), Scalar::Int64(7)];
14036 assert_eq!(
14037 infer_dtype(&values).expect("dtype should infer"),
14038 DType::Utf8
14039 );
14040 }
14041
14042 #[test]
14043 fn infer_dtype_routes_bool_numeric_mix_to_utf8_object_bucket_rh1od() {
14044 let values = vec![Scalar::Bool(true), Scalar::Int64(7), Scalar::Bool(false)];
14050 assert_eq!(
14051 infer_dtype(&values).expect("dtype should infer"),
14052 DType::Utf8
14053 );
14054 let with_float = vec![Scalar::Int64(1), Scalar::Float64(2.5), Scalar::Bool(true)];
14055 assert_eq!(
14056 infer_dtype(&with_float).expect("dtype should infer"),
14057 DType::Utf8
14058 );
14059 let with_null = vec![
14060 Scalar::Bool(true),
14061 Scalar::Null(NullKind::Null),
14062 Scalar::Int64(2),
14063 ];
14064 assert_eq!(
14065 infer_dtype(&with_null).expect("dtype should infer"),
14066 DType::Utf8
14067 );
14068 }
14069
14070 #[test]
14071 fn infer_dtype_keeps_nonmixed_bool_and_numeric_paths_rh1od() {
14072 assert_eq!(
14076 infer_dtype(&[Scalar::Bool(true), Scalar::Bool(false)]).expect("dtype should infer"),
14077 DType::Bool
14078 );
14079 assert_eq!(
14080 infer_dtype(&[Scalar::Int64(1), Scalar::Float64(2.5)]).expect("dtype should infer"),
14081 DType::Float64
14082 );
14083 }
14084
14085 #[test]
14088 fn is_null_detects_explicit_nulls() {
14089 assert!(Scalar::Null(NullKind::Null).is_null());
14090 assert!(Scalar::Null(NullKind::NaN).is_null());
14091 assert!(!Scalar::Int64(42).is_null());
14092 assert!(!Scalar::Float64(f64::NAN).is_null());
14093 }
14094
14095 #[test]
14096 fn is_na_matches_is_missing() {
14097 let vals = vec![
14098 Scalar::Null(NullKind::Null),
14099 Scalar::Float64(f64::NAN),
14100 Scalar::Int64(0),
14101 Scalar::Bool(false),
14102 ];
14103 for v in &vals {
14104 assert_eq!(v.is_na(), v.is_missing());
14105 }
14106 }
14107
14108 #[test]
14109 fn coalesce_picks_first_non_missing() {
14110 let null = Scalar::Null(NullKind::Null);
14111 let fill = Scalar::Int64(99);
14112 assert_eq!(null.coalesce(&fill), fill);
14113 assert_eq!(fill.coalesce(&null), fill);
14114 }
14115
14116 #[test]
14119 fn isna_notna_complement() {
14120 let vals = vec![
14121 Scalar::Int64(1),
14122 Scalar::Null(NullKind::Null),
14123 Scalar::Float64(f64::NAN),
14124 Scalar::Float64(3.0),
14125 ];
14126 let na = super::isna(&vals);
14127 let not = super::notna(&vals);
14128 assert_eq!(na, vec![false, true, true, false]);
14129 for (a, b) in na.iter().zip(not.iter()) {
14130 assert_ne!(a, b);
14131 }
14132 }
14133
14134 #[test]
14135 fn count_na_counts_missing() {
14136 let vals = vec![
14137 Scalar::Int64(1),
14138 Scalar::Null(NullKind::Null),
14139 Scalar::Float64(f64::NAN),
14140 ];
14141 assert_eq!(super::count_na(&vals), 2);
14142 }
14143
14144 #[test]
14145 fn fill_na_replaces_missing() {
14146 let vals = vec![
14147 Scalar::Int64(1),
14148 Scalar::Null(NullKind::Null),
14149 Scalar::Float64(f64::NAN),
14150 Scalar::Int64(4),
14151 ];
14152 let filled = super::fill_na(&vals, &Scalar::Int64(0));
14153 assert_eq!(filled[0], Scalar::Int64(1));
14154 assert_eq!(filled[1], Scalar::Int64(0));
14155 assert_eq!(filled[2], Scalar::Int64(0));
14156 assert_eq!(filled[3], Scalar::Int64(4));
14157 }
14158
14159 #[test]
14160 fn dropna_removes_missing() {
14161 let vals = vec![
14162 Scalar::Int64(1),
14163 Scalar::Null(NullKind::Null),
14164 Scalar::Int64(3),
14165 Scalar::Float64(f64::NAN),
14166 ];
14167 let kept = super::dropna(&vals);
14168 assert_eq!(kept.len(), 2);
14169 assert_eq!(kept[0], Scalar::Int64(1));
14170 assert_eq!(kept[1], Scalar::Int64(3));
14171 }
14172
14173 #[test]
14174 fn null_helpers_match_scalar_oracle_imt0c() {
14175 fn next(seed: &mut u64) -> u64 {
14178 *seed = seed
14179 .wrapping_mul(3202034522624059733)
14180 .wrapping_add(4354685564936845319);
14181 *seed
14182 }
14183
14184 fn assert_null_helpers(case: usize, values: &[Scalar], fill: &Scalar) {
14185 let expected_missing = values.iter().filter(|value| value.is_missing()).count();
14186 let expected_dropped = values
14187 .iter()
14188 .filter(|value| !value.is_missing())
14189 .cloned()
14190 .collect::<Vec<_>>();
14191 let expected_filled = values
14192 .iter()
14193 .map(|value| {
14194 if value.is_missing() {
14195 fill.clone()
14196 } else {
14197 value.clone()
14198 }
14199 })
14200 .collect::<Vec<_>>();
14201
14202 assert_eq!(
14203 super::count_na(values),
14204 expected_missing,
14205 "case={case}: count_na mismatch for {values:?}"
14206 );
14207
14208 let dropped = super::dropna(values);
14209 assert_eq!(
14210 dropped.len(),
14211 expected_dropped.len(),
14212 "case={case}: dropna length mismatch for {values:?}"
14213 );
14214 for (pos, (actual, expected)) in dropped.iter().zip(expected_dropped.iter()).enumerate()
14215 {
14216 assert!(
14217 actual.semantic_eq(expected),
14218 "case={case} pos={pos}: dropna expected {expected:?}, got {actual:?}"
14219 );
14220 }
14221
14222 let filled = super::fill_na(values, fill);
14223 assert_eq!(
14224 filled.len(),
14225 expected_filled.len(),
14226 "case={case}: fill_na length mismatch for {values:?}"
14227 );
14228 for (pos, (actual, expected)) in filled.iter().zip(expected_filled.iter()).enumerate() {
14229 assert!(
14230 actual.semantic_eq(expected),
14231 "case={case} pos={pos}: fill_na expected {expected:?}, got {actual:?}"
14232 );
14233 }
14234 }
14235
14236 let all_missing = [
14237 Scalar::Null(NullKind::Null),
14238 Scalar::Null(NullKind::NaN),
14239 Scalar::Float64(f64::NAN),
14240 Scalar::Timedelta64(i64::MIN),
14241 ];
14242 assert_null_helpers(usize::MAX, &all_missing, &Scalar::Utf8("filled".into()));
14243
14244 let mut seed = 0xc011_a7ed_0b5e_1a55_u64;
14245 for case in 0..260 {
14246 let len = (next(&mut seed) % 83 + 1) as usize;
14247 let mut values = Vec::with_capacity(len);
14248 for pos in 0..len {
14249 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
14250 values.push(match next(&mut seed) % 11 {
14251 0 => Scalar::Null(NullKind::Null),
14252 1 => Scalar::Null(NullKind::NaN),
14253 2 => Scalar::Float64(f64::NAN),
14254 3 => Scalar::Timedelta64(i64::MIN),
14255 4 => Scalar::Bool(raw & 1 == 0),
14256 5 => Scalar::Int64(raw),
14257 6 => Scalar::Float64(raw as f64 / 37.0),
14258 7 => Scalar::Float64(if raw & 1 == 0 { 0.0 } else { -0.0 }),
14259 8 => Scalar::Utf8(format!("null_helper_{case}_{pos}")),
14260 9 => Scalar::Utf8(String::new()),
14261 _ => Scalar::Timedelta64(raw),
14262 });
14263 }
14264
14265 let fill = match case % 5 {
14266 0 => Scalar::Bool(true),
14267 1 => Scalar::Int64(-777),
14268 2 => Scalar::Float64(12.5),
14269 3 => Scalar::Utf8("filled".into()),
14270 _ => Scalar::Timedelta64(123_456),
14271 };
14272 assert_null_helpers(case, &values, &fill);
14273 }
14274 }
14275
14276 #[test]
14279 fn nansum_skips_nulls() {
14280 let vals = vec![
14281 Scalar::Float64(1.0),
14282 Scalar::Null(NullKind::Null),
14283 Scalar::Float64(2.0),
14284 Scalar::Float64(f64::NAN),
14285 Scalar::Int64(7),
14286 ];
14287 assert_eq!(super::nansum(&vals), Scalar::Float64(10.0));
14288 }
14289
14290 #[test]
14291 fn nansum_empty_returns_zero() {
14292 assert_eq!(super::nansum(&[]), Scalar::Float64(0.0));
14293 }
14294
14295 #[test]
14296 fn nansum_nanmean_match_numeric_and_timedelta_oracle_1xmi7() {
14297 fn next(seed: &mut u64) -> u64 {
14300 *seed = seed
14301 .wrapping_mul(6364136223846793005)
14302 .wrapping_add(1442695040888963407);
14303 *seed
14304 }
14305
14306 fn expected_numeric(values: &[Scalar]) -> (Scalar, Scalar) {
14307 let mut sum = 0.0;
14308 let mut count = 0usize;
14309 for value in values {
14310 if value.is_missing() {
14311 continue;
14312 }
14313 if let Ok(value) = value.to_f64() {
14314 sum += value;
14315 count += 1;
14316 }
14317 }
14318 let mean = if count == 0 {
14319 Scalar::Null(NullKind::NaN)
14320 } else {
14321 Scalar::Float64(sum / count as f64)
14322 };
14323 (Scalar::Float64(sum), mean)
14324 }
14325
14326 fn expected_timedelta(values: &[Scalar]) -> (Scalar, Scalar) {
14327 let mut sum = 0_i128;
14328 let mut count = 0_i128;
14329 for value in values {
14330 if let Scalar::Timedelta64(ns) = value
14331 && !value.is_missing()
14332 {
14333 sum += i128::from(*ns);
14334 count += 1;
14335 }
14336 }
14337 if count == 0 {
14338 return (Scalar::Timedelta64(0), Scalar::Timedelta64(Timedelta::NAT));
14339 }
14340 (
14346 super::timedelta_ns_to_scalar(sum),
14347 super::timedelta_ns_to_scalar(sum / count),
14348 )
14349 }
14350
14351 fn assert_sum_mean(
14352 case: usize,
14353 family: &str,
14354 values: &[Scalar],
14355 expected_sum: Scalar,
14356 expected_mean: Scalar,
14357 ) {
14358 let actual_sum = super::nansum(values);
14359 let actual_mean = super::nanmean(values);
14360 assert!(
14361 actual_sum.semantic_eq(&expected_sum),
14362 "case={case} family={family}: expected sum {expected_sum:?}, got {actual_sum:?} for {values:?}"
14363 );
14364 assert!(
14365 actual_mean.semantic_eq(&expected_mean),
14366 "case={case} family={family}: expected mean {expected_mean:?}, got {actual_mean:?} for {values:?}"
14367 );
14368 }
14369
14370 let all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
14371 let (sum, mean) = expected_numeric(&all_missing);
14372 assert_sum_mean(usize::MAX, "numeric_all_missing", &all_missing, sum, mean);
14373
14374 let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
14375 let (sum, mean) = expected_timedelta(&td_all_missing);
14376 assert_sum_mean(
14377 usize::MAX - 1,
14378 "timedelta_all_missing",
14379 &td_all_missing,
14380 sum,
14381 mean,
14382 );
14383
14384 let mut seed = 0x511d_ed5a_7a11_1a55_u64;
14385 for case in 0..260 {
14386 let len = (next(&mut seed) % 89 + 1) as usize;
14387
14388 let mut numeric = Vec::with_capacity(len);
14389 numeric.push(Scalar::Int64(case as i64 - 130));
14390 for _ in 1..len {
14391 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
14392 numeric.push(match next(&mut seed) % 8 {
14393 0 => Scalar::Null(NullKind::Null),
14394 1 => Scalar::Null(NullKind::NaN),
14395 2 => Scalar::Float64(f64::NAN),
14396 3 => Scalar::Bool(raw & 1 == 0),
14397 4 => Scalar::Int64(raw % 257),
14398 5 => Scalar::Float64(raw as f64 / 67.0),
14399 6 => Scalar::Float64(0.0),
14400 _ => Scalar::Float64(-0.0),
14401 });
14402 }
14403 let (sum, mean) = expected_numeric(&numeric);
14404 assert_sum_mean(case, "numeric", &numeric, sum, mean);
14405
14406 let mut timedeltas = Vec::with_capacity(len);
14407 timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
14408 for _ in 1..len {
14409 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
14410 timedeltas.push(match next(&mut seed) % 7 {
14411 0 => Scalar::Null(NullKind::Null),
14412 1 => Scalar::Timedelta64(i64::MIN),
14413 _ => Scalar::Timedelta64(raw),
14414 });
14415 }
14416 let (sum, mean) = expected_timedelta(&timedeltas);
14417 assert_sum_mean(case, "timedelta", &timedeltas, sum, mean);
14418 }
14419 }
14420
14421 #[test]
14422 fn nannunique_merges_negative_zero_and_zero() {
14423 let vals = vec![
14424 Scalar::Float64(-0.0),
14425 Scalar::Float64(0.0),
14426 Scalar::Float64(1.0),
14427 ];
14428 assert_eq!(super::nannunique(&vals), Scalar::Int64(2));
14429 }
14430
14431 #[test]
14432 fn nannunique_matches_scalar_bucket_oracle_elvbg() {
14433 fn next(seed: &mut u64) -> u64 {
14436 *seed = seed
14437 .wrapping_mul(2862933555777941757)
14438 .wrapping_add(3037000493);
14439 *seed
14440 }
14441
14442 fn same_bucket(left: &Scalar, right: &Scalar) -> bool {
14443 match (left, right) {
14444 (Scalar::Float64(left), Scalar::Float64(right)) => {
14445 let left = if *left == 0.0 { 0.0 } else { *left };
14446 let right = if *right == 0.0 { 0.0 } else { *right };
14447 left.to_bits() == right.to_bits()
14448 }
14449 _ => left == right,
14450 }
14451 }
14452
14453 fn expected_nunique(values: &[Scalar]) -> i64 {
14454 let mut seen = Vec::<Scalar>::new();
14455 for value in values {
14456 if value.is_missing() {
14457 continue;
14458 }
14459 if !seen.iter().any(|existing| same_bucket(existing, value)) {
14460 seen.push(value.clone());
14461 }
14462 }
14463 seen.len() as i64
14464 }
14465
14466 fn assert_nannunique(case: usize, values: &[Scalar]) {
14467 assert_eq!(
14468 super::nannunique(values),
14469 Scalar::Int64(expected_nunique(values)),
14470 "case={case}: nannunique mismatch for {values:?}"
14471 );
14472 }
14473
14474 assert_nannunique(
14475 usize::MAX,
14476 &[
14477 Scalar::Float64(-0.0),
14478 Scalar::Float64(0.0),
14479 Scalar::Float64(f64::NAN),
14480 Scalar::Null(NullKind::Null),
14481 Scalar::Timedelta64(i64::MIN),
14482 ],
14483 );
14484
14485 let mut seed = 0x0e1b_60d0_b5e7_u64;
14486 for case in 0..320 {
14487 let len = (next(&mut seed) % 97 + 1) as usize;
14488 let mut values = Vec::with_capacity(len);
14489 for pos in 0..len {
14490 let raw = (next(&mut seed) % 1_001) as i64 - 500;
14491 values.push(match next(&mut seed) % 11 {
14492 0 => Scalar::Null(NullKind::Null),
14493 1 => Scalar::Null(NullKind::NaN),
14494 2 => Scalar::Float64(f64::NAN),
14495 3 => Scalar::Bool(raw & 1 == 0),
14496 4 => Scalar::Int64(raw % 37),
14497 5 => Scalar::Float64(raw as f64 / 19.0),
14498 6 => Scalar::Float64(0.0),
14499 7 => Scalar::Float64(-0.0),
14500 8 => Scalar::Utf8(format!("uniq_{}", pos % 13)),
14501 9 => Scalar::Utf8(String::new()),
14502 _ => Scalar::Timedelta64(raw % 41),
14503 });
14504 }
14505 assert_nannunique(case, &values);
14506 }
14507 }
14508
14509 #[test]
14510 fn nanmean_basic() {
14511 let vals = vec![
14512 Scalar::Float64(2.0),
14513 Scalar::Null(NullKind::Null),
14514 Scalar::Float64(4.0),
14515 ];
14516 assert_eq!(super::nanmean(&vals), Scalar::Float64(3.0));
14517 }
14518
14519 #[test]
14520 fn nanmean_all_null_returns_nan() {
14521 let vals = vec![Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
14522 assert!(super::nanmean(&vals).is_missing());
14523 }
14524
14525 #[test]
14526 fn nansum_nanmean_timedelta64_preserves_dtype_620mj() {
14527 let one_hour = 3_600 * 1_000_000_000_i64;
14531 let vals = vec![
14532 Scalar::Timedelta64(one_hour),
14533 Scalar::Timedelta64(2 * one_hour),
14534 Scalar::Timedelta64(3 * one_hour),
14535 ];
14536 assert_eq!(super::nansum(&vals), Scalar::Timedelta64(6 * one_hour));
14537 assert_eq!(super::nanmean(&vals), Scalar::Timedelta64(2 * one_hour));
14538 }
14539
14540 #[test]
14541 fn nansum_nanmean_timedelta64_skips_nat_620mj() {
14542 let one_hour = 3_600 * 1_000_000_000_i64;
14543 let vals = vec![
14544 Scalar::Timedelta64(Timedelta::NAT),
14545 Scalar::Timedelta64(one_hour),
14546 Scalar::Timedelta64(3 * one_hour),
14547 Scalar::Timedelta64(Timedelta::NAT),
14548 ];
14549 assert_eq!(super::nansum(&vals), Scalar::Timedelta64(4 * one_hour));
14551 assert_eq!(super::nanmean(&vals), Scalar::Timedelta64(2 * one_hour));
14552 }
14553
14554 #[test]
14561 fn nansum_timedelta_overflow_is_nat_not_fabricated_max_opz27() {
14562 let vals = vec![Scalar::Timedelta64(i64::MAX), Scalar::Timedelta64(i64::MAX)];
14563 let got = super::nansum(&vals);
14564 assert!(
14565 got.is_missing(),
14566 "overflowing sum must be missing, got {got:?}"
14567 );
14568 assert_eq!(got, Scalar::Timedelta64(Timedelta::NAT));
14569 assert_ne!(got, Scalar::Timedelta64(i64::MAX));
14570 }
14571
14572 #[test]
14577 fn nansum_timedelta_negative_overflow_is_nat_opz27() {
14578 let min_repr = i64::MIN + 1; let vals = vec![Scalar::Timedelta64(min_repr), Scalar::Timedelta64(min_repr)];
14580 assert_eq!(super::nansum(&vals), Scalar::Timedelta64(Timedelta::NAT));
14581
14582 let exact = vec![Scalar::Timedelta64(min_repr + 1), Scalar::Timedelta64(-1)];
14585 let got = super::nansum(&exact);
14586 assert_eq!(got, Scalar::Timedelta64(min_repr));
14587 assert!(!got.is_missing(), "Timedelta.min is representable, not NaT");
14588 }
14589
14590 #[test]
14594 fn nanptp_timedelta_overflow_is_nat_opz27() {
14595 let vals = vec![
14596 Scalar::Timedelta64(i64::MIN + 1),
14597 Scalar::Timedelta64(i64::MAX),
14598 ];
14599 let got = super::nanptp(&vals);
14600 assert!(
14601 got.is_missing(),
14602 "unrepresentable range must be NaT, got {got:?}"
14603 );
14604 assert_ne!(got, Scalar::Timedelta64(i64::MAX));
14605
14606 let hour = 3_600 * 1_000_000_000_i64;
14609 let ok = vec![Scalar::Timedelta64(hour), Scalar::Timedelta64(4 * hour)];
14610 assert_eq!(super::nanptp(&ok), Scalar::Timedelta64(3 * hour));
14611 }
14612
14613 #[test]
14618 fn nancumsum_timedelta_overflow_recovers_exact_value_opz27() {
14619 let vals = vec![
14620 Scalar::Timedelta64(i64::MAX),
14621 Scalar::Timedelta64(i64::MAX), Scalar::Timedelta64(i64::MIN + 1), ];
14624 let out = super::nancumsum(&vals);
14625 assert_eq!(out.len(), 3);
14626 assert_eq!(out[0], Scalar::Timedelta64(i64::MAX));
14627 assert!(
14628 out[1].is_missing(),
14629 "overflowed index must be NaT, got {:?}",
14630 out[1]
14631 );
14632 assert_eq!(
14633 out[2],
14634 Scalar::Timedelta64(i64::MAX),
14635 "exact i128 accumulation must recover; a clamped running sum cannot"
14636 );
14637 }
14638
14639 #[test]
14642 fn nancumsum_timedelta_exact_path_unchanged_opz27() {
14643 let sec = 1_000_000_000_i64;
14644 let vals = vec![
14645 Scalar::Timedelta64(sec),
14646 Scalar::Timedelta64(Timedelta::NAT),
14647 Scalar::Timedelta64(2 * sec),
14648 ];
14649 let out = super::nancumsum(&vals);
14650 assert_eq!(out[0], Scalar::Timedelta64(sec));
14651 assert!(out[1].is_missing());
14652 assert_eq!(out[2], Scalar::Timedelta64(3 * sec));
14653 }
14654
14655 const DAY_NS: i64 = 86_400 * 1_000_000_000;
14656 const DT_2020: i64 = 1_577_836_800_000_000_000;
14658
14659 #[test]
14667 fn datetime64_ordering_reductions_match_pandas_axhhk() {
14668 let d = Scalar::Datetime64;
14669 let vals = vec![
14670 d(DT_2020),
14671 d(DT_2020 + 60 * DAY_NS),
14672 d(DT_2020 + 31 * DAY_NS),
14673 ];
14674
14675 assert_eq!(super::nanmin(&vals), d(DT_2020));
14676 assert_eq!(super::nanmax(&vals), d(DT_2020 + 60 * DAY_NS));
14677 assert_eq!(super::nanargmin(&vals), Some(0));
14678 assert_eq!(super::nanargmax(&vals), Some(1));
14679
14680 let span = super::nanptp(&vals);
14682 assert_eq!(span, Scalar::Timedelta64(60 * DAY_NS));
14683 assert_eq!(span.dtype(), DType::Timedelta64);
14684
14685 assert_eq!(
14686 super::nancummax(&vals),
14687 vec![
14688 d(DT_2020),
14689 d(DT_2020 + 60 * DAY_NS),
14690 d(DT_2020 + 60 * DAY_NS)
14691 ]
14692 );
14693 assert_eq!(
14694 super::nancummin(&vals),
14695 vec![d(DT_2020), d(DT_2020), d(DT_2020)]
14696 );
14697 }
14698
14699 #[test]
14706 fn datetime64_min_max_size_dependence_pinned_axhhk() {
14707 let d = Scalar::Datetime64;
14708 let one = vec![d(DT_2020)];
14709 assert_eq!(super::nanmin(&one), d(DT_2020));
14710 assert_eq!(super::nanmax(&one), d(DT_2020));
14711
14712 let two = vec![d(DT_2020 + DAY_NS), d(DT_2020)];
14713 let got_min = super::nanmin(&two);
14714 assert!(
14715 !got_min.is_missing(),
14716 "2-element datetime min must not be missing, got {got_min:?}"
14717 );
14718 assert_eq!(got_min, d(DT_2020));
14719 assert_eq!(super::nanmax(&two), d(DT_2020 + DAY_NS));
14720 }
14721
14722 #[test]
14725 fn datetime64_reductions_skip_nat_and_guard_span_overflow_axhhk() {
14726 let d = Scalar::Datetime64;
14727 let with_nat = vec![
14728 d(Timestamp::NAT),
14729 d(DT_2020 + 31 * DAY_NS),
14730 d(DT_2020),
14731 d(Timestamp::NAT),
14732 ];
14733 assert_eq!(super::nanmin(&with_nat), d(DT_2020));
14734 assert_eq!(super::nanmax(&with_nat), d(DT_2020 + 31 * DAY_NS));
14735 assert_eq!(super::nanptp(&with_nat), Scalar::Timedelta64(31 * DAY_NS));
14736 assert_eq!(super::nanargmin(&with_nat), Some(2));
14738 assert_eq!(super::nanargmax(&with_nat), Some(1));
14739
14740 let huge = vec![d(i64::MIN + 1), d(i64::MAX)];
14742 let span = super::nanptp(&huge);
14743 assert!(span.is_missing(), "unrepresentable span must be NaT");
14744 assert_ne!(span, Scalar::Timedelta64(i64::MAX));
14745 }
14746
14747 #[test]
14754 fn datetime64_averaging_reductions_match_pandas_adv58() {
14755 let d = Scalar::Datetime64;
14756 let vals = vec![
14757 d(DT_2020),
14758 d(DT_2020 + 60 * DAY_NS),
14759 d(DT_2020 + 31 * DAY_NS),
14760 ];
14761 assert_eq!(super::nanmean(&vals), d(1_580_457_600_000_000_000));
14763 assert_eq!(super::nanmedian(&vals), d(1_580_515_200_000_000_000));
14764 assert_eq!(super::nanquantile(&vals, 0.5), d(1_580_515_200_000_000_000));
14765 assert_eq!(
14766 super::nanquantile(&vals, 0.25),
14767 d(1_579_176_000_000_000_000)
14768 );
14769 }
14770
14771 #[test]
14777 fn datetime64_mean_median_round_toward_zero_adv58() {
14778 let d = Scalar::Datetime64;
14779 for (a, b, want) in [
14780 (0_i64, 1_i64, 0_i64),
14781 (0, 3, 1),
14782 (1, 2, 1),
14783 (-1, 0, 0),
14784 (-3, 0, -1),
14785 (-2, -1, -1),
14786 (0, 2, 1),
14787 (-2, 0, -1),
14788 ] {
14789 let vals = vec![d(a), d(b)];
14790 assert_eq!(
14791 super::nanmean(&vals),
14792 d(want),
14793 "mean of [{a}, {b}] should be {want}"
14794 );
14795 assert_eq!(
14796 super::nanmedian(&vals),
14797 d(want),
14798 "median of [{a}, {b}] should be {want}"
14799 );
14800 }
14801 }
14802
14803 #[test]
14806 fn datetime64_averaging_skips_nat_adv58() {
14807 let d = Scalar::Datetime64;
14808 let vals = vec![d(DT_2020), d(Timestamp::NAT), d(DT_2020 + 2 * DAY_NS)];
14809 assert_eq!(super::nanmean(&vals), d(DT_2020 + DAY_NS));
14811 assert_eq!(super::nanmedian(&vals), d(DT_2020 + DAY_NS));
14812
14813 let all_nat = vec![d(Timestamp::NAT), d(Timestamp::NAT)];
14814 let got = super::nanmean(&all_nat);
14815 assert!(
14816 got.is_missing(),
14817 "all-NaT mean must be missing, got {got:?}"
14818 );
14819 assert_eq!(
14820 got.dtype(),
14821 DType::datetime64_naive(),
14822 "must stay Datetime64"
14823 );
14824 }
14825
14826 #[test]
14833 fn datetime64_averaging_is_exact_where_pandas_snaps_adv58() {
14834 let d = Scalar::Datetime64;
14835
14836 let constant = vec![d(DT_2020 + 1), d(DT_2020 + 1)];
14838 assert_eq!(super::nanmean(&constant), d(DT_2020 + 1));
14839 assert_eq!(super::nanmedian(&constant), d(DT_2020 + 1));
14840
14841 let odd = vec![d(DT_2020), d(DT_2020 + 129), d(DT_2020 + 258)];
14843 let med = super::nanmedian(&odd);
14844 assert_eq!(med, d(DT_2020 + 129));
14845 assert!(
14846 odd.contains(&med),
14847 "odd-count median must be one of the inputs; pandas returns B+256, which is not"
14848 );
14849 }
14850
14851 #[test]
14858 fn datetime64_std_matches_pandas_ddof_variants_40ujm() {
14859 let d = Scalar::Datetime64;
14860 let vals = vec![
14861 d(DT_2020),
14862 d(DT_2020 + 60 * DAY_NS),
14863 d(DT_2020 + 31 * DAY_NS),
14864 ];
14865 let s1 = super::nanstd(&vals, 1);
14867 assert_eq!(s1, Scalar::Timedelta64(2_592_479_955_563_784));
14868 assert_eq!(s1.dtype(), DType::Timedelta64);
14869 assert_eq!(
14870 super::nanstd(&vals, 0),
14871 Scalar::Timedelta64(2_116_751_019_841_492)
14872 );
14873 assert_eq!(
14874 super::nanstd(&vals, 2),
14875 Scalar::Timedelta64(3_666_320_313_338_702)
14876 );
14877 assert!(super::nanstd(&vals, 3).is_missing());
14879 }
14880
14881 #[test]
14885 fn datetime64_std_equals_timedelta64_std_on_same_ns_40ujm() {
14886 let offsets = [0_i64, 60 * DAY_NS, 31 * DAY_NS];
14887 let dt: Vec<Scalar> = offsets.iter().map(|o| Scalar::Datetime64(*o)).collect();
14888 let td: Vec<Scalar> = offsets.iter().map(|o| Scalar::Timedelta64(*o)).collect();
14889 assert_eq!(super::nanstd(&dt, 1), super::nanstd(&td, 1));
14890 assert_eq!(
14891 super::nanstd(&dt, 1),
14892 Scalar::Timedelta64(2_592_479_955_563_784)
14893 );
14894 }
14895
14896 #[test]
14900 fn datetime64_std_skips_nat_and_var_sem_stay_unsupported_40ujm() {
14901 let d = Scalar::Datetime64;
14902 let with_nat = vec![d(DT_2020), d(Timestamp::NAT), d(DT_2020 + 2 * DAY_NS)];
14903 let without = vec![d(DT_2020), d(DT_2020 + 2 * DAY_NS)];
14904 assert_eq!(super::nanstd(&with_nat, 1), super::nanstd(&without, 1));
14906 assert_eq!(
14907 super::nanstd(&with_nat, 1),
14908 Scalar::Timedelta64(122_188_051_789_035)
14909 );
14910
14911 assert!(super::nanstd(&[d(DT_2020)], 1).is_missing());
14913 assert!(super::nanstd(&[d(Timestamp::NAT)], 1).is_missing());
14914
14915 let vals = vec![d(DT_2020), d(DT_2020 + 60 * DAY_NS)];
14919 assert!(super::nanvar(&vals, 1).is_missing());
14920 assert!(super::nansem(&vals, 1).is_missing());
14921 }
14922
14923 #[test]
14928 fn period_min_max_match_pandas_qoabs() {
14929 let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
14930 let vals = vec![p(600), p(602), p(601)];
14931 assert_eq!(super::nanmin(&vals), p(600));
14932 assert_eq!(super::nanmax(&vals), p(602));
14933
14934 assert_eq!(super::nanmin(&[p(600)]), p(600));
14938 let two = vec![p(602), p(600)];
14939 assert!(!super::nanmin(&two).is_missing());
14940 assert_eq!(super::nanmin(&two), p(600));
14941 assert_eq!(super::nanmax(&two), p(602));
14942 }
14943
14944 #[test]
14947 fn period_min_max_skip_nat_qoabs() {
14948 let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
14949 let nat = Scalar::Period(Period::new(i64::MIN, PeriodFreq::Monthly));
14950 let vals = vec![nat.clone(), p(602), p(600), nat.clone()];
14951 assert_eq!(super::nanmin(&vals), p(600));
14952 assert_eq!(super::nanmax(&vals), p(602));
14953 assert!(super::nanmin(&[nat.clone(), nat]).is_missing());
14954 }
14955
14956 #[test]
14963 fn period_mixed_freq_is_not_ordered_qoabs() {
14964 let month = Scalar::Period(Period::new(600, PeriodFreq::Monthly));
14965 let day = Scalar::Period(Period::new(18_267, PeriodFreq::Daily));
14966 let vals = vec![month.clone(), day.clone()];
14967 let got_min = super::nanmin(&vals);
14968 assert!(
14969 got_min.is_missing(),
14970 "mixed-freq Period min must not be ordered, got {got_min:?}"
14971 );
14972 assert_ne!(
14973 got_min, day,
14974 "must not rank the daily period by raw ordinal"
14975 );
14976 assert!(super::nanmax(&vals).is_missing());
14977 }
14978
14979 #[test]
14986 fn period_full_reduction_family_matches_pandas_d7zjp() {
14987 let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
14988 let vals = vec![p(600), p(602), p(601)];
14989
14990 assert_eq!(super::nanmedian(&vals), p(601));
14991 assert_eq!(super::nanquantile(&vals, 0.5), p(601));
14992 assert_eq!(super::nanargmin(&vals), Some(0));
14993 assert_eq!(super::nanargmax(&vals), Some(1));
14994 assert_eq!(super::nancummax(&vals), vec![p(600), p(602), p(602)]);
14995 assert_eq!(super::nancummin(&vals), vec![p(600), p(600), p(600)]);
14996 }
14997
14998 #[test]
15003 fn period_even_count_median_truncates_toward_zero_d7zjp() {
15004 let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
15005 assert_eq!(super::nanmedian(&[p(600), p(603)]), p(601));
15006 assert_eq!(super::nanmedian(&[p(600), p(601)]), p(600));
15007 }
15008
15009 #[test]
15015 fn period_mixed_freq_not_ordered_by_any_reduction_d7zjp() {
15016 let month = Scalar::Period(Period::new(600, PeriodFreq::Monthly));
15017 let day = Scalar::Period(Period::new(18_267, PeriodFreq::Daily));
15018 let vals = vec![month, day];
15019
15020 assert!(super::nanmedian(&vals).is_missing());
15021 assert!(super::nanquantile(&vals, 0.5).is_missing());
15022 assert_eq!(super::nanargmin(&vals), None);
15023 assert_eq!(super::nanargmax(&vals), None);
15024 assert!(super::nancummax(&vals).iter().all(Scalar::is_missing));
15026 assert!(super::nancummin(&vals).iter().all(Scalar::is_missing));
15027 }
15028
15029 #[test]
15035 fn period_unsupported_reductions_stay_missing_d7zjp() {
15036 let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
15037 let vals = vec![p(600), p(602), p(601)];
15038 assert!(super::nanstd(&vals, 1).is_missing(), "pandas raises std");
15039 assert!(super::nanvar(&vals, 1).is_missing(), "pandas raises var");
15040 assert!(super::nansem(&vals, 1).is_missing(), "pandas raises sem");
15041 assert!(super::nanmean(&vals).is_missing(), "pandas raises mean");
15042 }
15043
15044 #[test]
15049 fn interval_min_max_match_pandas_srqdo() {
15050 let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
15051 let vals = vec![iv(0.0, 1.0), iv(4.0, 5.0), iv(2.0, 3.0)];
15052 assert_eq!(super::nanmin(&vals), iv(0.0, 1.0));
15053 assert_eq!(super::nanmax(&vals), iv(4.0, 5.0));
15054
15055 assert_eq!(super::nanmin(&[iv(2.0, 3.0)]), iv(2.0, 3.0));
15058 let two = vec![iv(4.0, 5.0), iv(0.0, 1.0)];
15059 assert!(!super::nanmin(&two).is_missing());
15060 assert_eq!(super::nanmin(&two), iv(0.0, 1.0));
15061 assert_eq!(super::nanmax(&two), iv(4.0, 5.0));
15062 }
15063
15064 #[test]
15069 fn interval_ties_on_left_order_by_right_srqdo() {
15070 let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
15071 let vals = vec![iv(0.0, 5.0), iv(0.0, 2.0), iv(0.0, 9.0)];
15072 assert_eq!(super::nanmin(&vals), iv(0.0, 2.0));
15073 assert_eq!(super::nanmax(&vals), iv(0.0, 9.0));
15074 }
15075
15076 #[test]
15082 fn interval_nan_bound_is_not_ordered_srqdo() {
15083 let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
15084 let vals = vec![iv(0.0, 1.0), iv(f64::NAN, 5.0)];
15085 assert!(super::nanmin(&vals).is_missing());
15086 assert!(super::nanmax(&vals).is_missing());
15087 }
15088
15089 #[test]
15093 fn interval_unsupported_reductions_stay_missing_srqdo() {
15094 let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
15095 let vals = vec![iv(0.0, 1.0), iv(4.0, 5.0), iv(2.0, 3.0)];
15096 assert!(super::nanmedian(&vals).is_missing(), "pandas raises median");
15097 assert!(super::nanmean(&vals).is_missing(), "pandas raises mean");
15098 assert!(super::nanstd(&vals, 1).is_missing(), "pandas raises std");
15099 assert!(
15100 super::nanquantile(&vals, 0.5).is_missing(),
15101 "pandas raises quantile"
15102 );
15103 assert!(
15104 super::nancummax(&vals).iter().all(Scalar::is_missing),
15105 "pandas NotImplementedErrors cummax"
15106 );
15107 }
15108
15109 #[test]
15113 fn interval_argmin_argmax_match_pandas_2h9dm() {
15114 let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
15115 let vals = vec![iv(4.0, 5.0), iv(0.0, 1.0), iv(2.0, 3.0)];
15117 assert_eq!(super::nanargmin(&vals), Some(1));
15118 assert_eq!(super::nanargmax(&vals), Some(0));
15119
15120 let tie = vec![iv(0.0, 5.0), iv(0.0, 2.0), iv(0.0, 9.0)];
15123 assert_eq!(super::nanargmin(&tie), Some(1));
15124 assert_eq!(super::nanargmax(&tie), Some(2));
15125 }
15126
15127 #[test]
15132 fn interval_arg_first_occurrence_and_missing_2h9dm() {
15133 let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
15134 let dup = vec![iv(0.0, 1.0), iv(0.0, 1.0), iv(9.0, 9.0)];
15135 assert_eq!(
15136 super::nanargmin(&dup),
15137 Some(0),
15138 "first occurrence, not last"
15139 );
15140 assert_eq!(super::nanargmax(&dup), Some(2));
15141
15142 let with_missing = vec![iv(4.0, 5.0), Scalar::Null(NullKind::NaN), iv(0.0, 1.0)];
15143 assert_eq!(super::nanargmin(&with_missing), Some(2));
15144 assert_eq!(super::nanargmax(&with_missing), Some(0));
15145 }
15146
15147 #[test]
15151 fn interval_arg_nan_bound_declines_2h9dm() {
15152 let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
15153 let vals = vec![iv(0.0, 1.0), iv(f64::NAN, 5.0)];
15154 assert_eq!(super::nanargmin(&vals), None);
15155 assert_eq!(super::nanargmax(&vals), None);
15156 }
15157
15158 #[test]
15165 fn overflow_policy_carrier_preserves_default_behavior_f29nz() {
15166 let mut state: u64 = 0x5DEE_CE66_D125_1F00;
15168 let mut next = || {
15169 state = state
15170 .wrapping_mul(6_364_136_223_846_793_005)
15171 .wrapping_add(1_442_695_040_888_963_407);
15172 state
15173 };
15174 let mut corpus: Vec<i64> = vec![
15176 0,
15177 1,
15178 -1,
15179 2,
15180 -2,
15181 i64::MAX,
15182 i64::MIN,
15183 i64::MIN + 1,
15184 i64::MAX - 1,
15185 i64::MAX / 2,
15186 -(i64::MAX / 2),
15187 ];
15188 for _ in 0..400 {
15189 let raw = next() as i64;
15190 corpus.push(raw);
15191 corpus.push(raw / 3);
15192 }
15193
15194 let policy = super::OverflowPolicy::default();
15195 assert_eq!(
15196 policy,
15197 super::OverflowPolicy::SurfaceNat,
15198 "default must not move"
15199 );
15200
15201 for &a in &corpus {
15202 for &b in &corpus {
15203 assert_eq!(
15205 Timedelta::add(a, b),
15206 policy
15207 .resolve(Timedelta::try_add(a, b), Timedelta::NAT)
15208 .expect("SurfaceNat never errors"),
15209 "add({a}, {b}) diverged"
15210 );
15211 assert_eq!(
15212 Timedelta::sub(a, b),
15213 policy
15214 .resolve(Timedelta::try_sub(a, b), Timedelta::NAT)
15215 .expect("SurfaceNat never errors"),
15216 "sub({a}, {b}) diverged"
15217 );
15218 assert_eq!(
15219 Timedelta::mul_scalar(a, b),
15220 policy
15221 .resolve(Timedelta::try_mul_scalar(a, b), Timedelta::NAT)
15222 .expect("SurfaceNat never errors"),
15223 "mul_scalar({a}, {b}) diverged"
15224 );
15225
15226 let ts = Timestamp::from_nanos(a);
15229 assert_eq!(
15230 ts.add_timedelta(b),
15231 ts.try_add_timedelta(b).unwrap_or_else(|_| Timestamp::nat()),
15232 "add_timedelta({a}, {b}) diverged"
15233 );
15234 assert_eq!(
15235 ts.sub_timedelta(b),
15236 ts.try_sub_timedelta(b).unwrap_or_else(|_| Timestamp::nat()),
15237 "sub_timedelta({a}, {b}) diverged"
15238 );
15239 let other = Timestamp::from_nanos(b);
15240 assert_eq!(
15241 ts.sub_timestamp(&other),
15242 ts.try_sub_timestamp(&other).unwrap_or(Timedelta::NAT),
15243 "sub_timestamp({a}, {b}) diverged"
15244 );
15245 }
15246 }
15247 }
15248
15249 #[test]
15254 fn overflow_policy_strict_reports_op_and_pandas_class_f29nz() {
15255 use super::{OverflowPolicy, PandasTemporalError};
15256
15257 let strict = OverflowPolicy::Strict;
15258
15259 let err = strict
15261 .resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT)
15262 .expect_err("must surface under Strict");
15263 assert_eq!(err.op, "Timedelta::add");
15264 assert_eq!(err.pandas_error, PandasTemporalError::Overflow);
15265
15266 let ts = Timestamp::from_nanos(i64::MAX);
15268 let err = strict
15269 .resolve(ts.try_add_timedelta(1), Timestamp::nat())
15270 .expect_err("must surface under Strict");
15271 assert_eq!(err.op, "Timestamp::add_timedelta");
15272 assert_eq!(err.pandas_error, PandasTemporalError::OutOfBoundsDatetime);
15273
15274 let err = strict
15276 .resolve(
15277 Timestamp::from_nanos(i64::MIN + 1)
15278 .try_sub_timestamp(&Timestamp::from_nanos(i64::MAX)),
15279 Timedelta::NAT,
15280 )
15281 .expect_err("must surface under Strict");
15282 assert_eq!(err.op, "Timestamp::sub_timestamp");
15283 assert_eq!(err.pandas_error, PandasTemporalError::OutOfBoundsDatetime);
15284
15285 assert_eq!(
15287 strict
15288 .resolve(Timedelta::try_add(Timedelta::NAT, 1), Timedelta::NAT)
15289 .expect("NaT propagation is not an overflow"),
15290 Timedelta::NAT
15291 );
15292 assert_eq!(
15294 strict
15295 .resolve(Timedelta::try_add(2, 3), Timedelta::NAT)
15296 .expect("no overflow"),
15297 5
15298 );
15299 }
15300
15301 #[test]
15309 fn timedelta_scalar_zero_division_taxonomy_t7ht2() {
15310 use super::{OverflowPolicy, PandasTemporalError};
15311
15312 let err = Timedelta::try_div_scalar(1_000_000_000, 0)
15314 .expect_err("scalar divide-by-zero must be reportable");
15315 assert_eq!(err.op, "Timedelta::div_scalar");
15316 assert_eq!(err.pandas_error, PandasTemporalError::ZeroDivision);
15317
15318 assert_eq!(Timedelta::div_scalar(1_000_000_000, 0), Timedelta::NAT);
15322 assert_eq!(Timedelta::div_scalar(Timedelta::NAT, 0), Timedelta::NAT);
15323
15324 assert_eq!(
15327 OverflowPolicy::default()
15328 .resolve(Timedelta::try_div_scalar(1_000_000_000, 0), Timedelta::NAT)
15329 .expect("SurfaceNat never errors"),
15330 Timedelta::NAT
15331 );
15332
15333 assert_eq!(Timedelta::try_div_scalar(-7, 2), Ok(-4));
15336 assert_eq!(Timedelta::div_scalar(-7, 2), -4);
15337 assert_eq!(Timedelta::try_div_scalar(7, 2), Ok(3));
15338 assert_eq!(
15340 Timedelta::try_div_scalar(Timedelta::NAT, 2),
15341 Ok(Timedelta::NAT)
15342 );
15343 }
15344
15345 #[test]
15350 fn timedelta_constructor_error_maps_to_out_of_bounds_t7ht2() {
15351 use super::{PandasTemporalError, TimedeltaError};
15352
15353 assert_eq!(
15354 TimedeltaError::Overflow.pandas_error(),
15355 Some(PandasTemporalError::OutOfBoundsTimedelta)
15356 );
15357 assert_eq!(
15359 TimedeltaError::InvalidFormat("nonsense".into()).pandas_error(),
15360 None
15361 );
15362 assert!(Timedelta::from_unit(f64::INFINITY, "s").is_err());
15364 assert_eq!(
15365 Timedelta::from_unit(f64::INFINITY, "s")
15366 .unwrap_err()
15367 .pandas_error(),
15368 Some(PandasTemporalError::OutOfBoundsTimedelta)
15369 );
15370 }
15371
15372 #[test]
15378 fn hardened_audit_values_are_bit_identical_to_surface_nat_vllv6() {
15379 use super::{OverflowPolicy, overflow_audit};
15380
15381 overflow_audit::enable();
15382 let mut state: u64 = 0x1234_5678_9ABC_DEF0;
15383 let mut next = || {
15384 state = state
15385 .wrapping_mul(6_364_136_223_846_793_005)
15386 .wrapping_add(1_442_695_040_888_963_407);
15387 state
15388 };
15389 let mut corpus: Vec<i64> = vec![
15390 0,
15391 1,
15392 -1,
15393 2,
15394 -2,
15395 i64::MAX,
15396 i64::MIN,
15397 i64::MIN + 1,
15398 i64::MAX - 1,
15399 ];
15400 for _ in 0..120 {
15401 corpus.push(next() as i64);
15402 }
15403
15404 for &a in &corpus {
15405 for &b in &corpus {
15406 for op in [
15407 Timedelta::try_add as fn(i64, i64) -> Result<i64, super::TemporalFailure>,
15408 Timedelta::try_sub,
15409 Timedelta::try_mul_scalar,
15410 Timedelta::try_div_scalar,
15411 ] {
15412 let soft = OverflowPolicy::SurfaceNat
15413 .resolve(op(a, b), Timedelta::NAT)
15414 .expect("SurfaceNat never errors");
15415 let hard = OverflowPolicy::HardenedNat
15416 .resolve(op(a, b), Timedelta::NAT)
15417 .expect("HardenedNat never errors");
15418 assert_eq!(hard, soft, "HARDENED changed a value for ({a}, {b})");
15419 }
15420 }
15421 }
15422 overflow_audit::disable();
15423 }
15424
15425 #[test]
15430 fn hardened_audit_records_deterministic_recovery_entries_vllv6() {
15431 use super::{OverflowPolicy, PandasTemporalError, overflow_audit};
15432
15433 overflow_audit::enable();
15434 assert!(overflow_audit::is_enabled());
15435 assert!(overflow_audit::drain().is_empty(), "starts empty");
15436
15437 let _ =
15439 OverflowPolicy::HardenedNat.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
15440 let _ = OverflowPolicy::HardenedNat.resolve(Timedelta::try_add(2, 3), Timedelta::NAT);
15441 let _ =
15442 OverflowPolicy::HardenedNat.resolve(Timedelta::try_div_scalar(5, 0), Timedelta::NAT);
15443
15444 let entries = overflow_audit::drain();
15445 assert_eq!(entries.len(), 2, "only the two failures are recorded");
15446
15447 assert_eq!(entries[0].op, "Timedelta::add");
15448 assert_eq!(entries[0].pandas_error, PandasTemporalError::Overflow);
15449 assert_eq!(entries[0].operands, Some((i64::MAX, 1)));
15450 assert_eq!(entries[0].recovered_as, i64::MIN);
15451
15452 assert_eq!(entries[1].op, "Timedelta::div_scalar");
15453 assert_eq!(entries[1].pandas_error, PandasTemporalError::ZeroDivision);
15454 assert_eq!(entries[1].operands, Some((5, 0)));
15455
15456 assert!(overflow_audit::drain().is_empty());
15458
15459 let _ = OverflowPolicy::SurfaceNat.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
15461 let _ = OverflowPolicy::Strict.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
15462 assert!(
15463 overflow_audit::drain().is_empty(),
15464 "SurfaceNat/Strict must not write to the audit trail"
15465 );
15466
15467 overflow_audit::disable();
15468 assert!(!overflow_audit::is_enabled());
15469 let _ =
15471 OverflowPolicy::HardenedNat.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
15472 assert!(
15473 overflow_audit::drain().is_empty(),
15474 "disabled must not record"
15475 );
15476 }
15477
15478 #[test]
15496 fn strict_reproduces_pandas_silent_timedelta_wrap_s4lkx() {
15497 use super::{OverflowPolicy, nancumsum_with_policy};
15498
15499 assert_eq!(
15501 Timedelta::mul_scalar_with_policy(i64::MAX, 2, OverflowPolicy::Strict),
15502 -2,
15503 "STRICT must reproduce pandas' wrap, not repair it"
15504 );
15505
15506 let max = Scalar::Timedelta64(i64::MAX);
15509 let out = nancumsum_with_policy(
15510 &[max.clone(), max.clone(), max.clone()],
15511 OverflowPolicy::Strict,
15512 );
15513 assert_eq!(
15514 out,
15515 vec![
15516 Scalar::Timedelta64(i64::MAX),
15517 Scalar::Timedelta64(-2),
15518 Scalar::Timedelta64(i64::MAX - 2),
15519 ],
15520 "STRICT cumsum must reproduce pandas' int64 wraparound exactly"
15521 );
15522
15523 assert_eq!(
15525 Timedelta::mul_scalar_with_policy(Timedelta::NAT, 2, OverflowPolicy::Strict),
15526 Timedelta::NAT
15527 );
15528 }
15529
15530 #[test]
15536 fn non_strict_policies_still_refuse_to_wrap_s4lkx() {
15537 use super::{OverflowPolicy, nancumsum_with_policy, overflow_audit};
15538
15539 for policy in [OverflowPolicy::SurfaceNat, OverflowPolicy::HardenedNat] {
15540 assert_eq!(
15541 Timedelta::mul_scalar_with_policy(i64::MAX, 2, policy),
15542 Timedelta::NAT,
15543 "{policy:?} must NOT wrap"
15544 );
15545 assert_ne!(
15546 Timedelta::mul_scalar_with_policy(i64::MAX, 2, policy),
15547 -2,
15548 "{policy:?} must not reproduce the pandas quirk"
15549 );
15550 }
15551 assert_eq!(
15553 Timedelta::mul_scalar_with_policy(i64::MAX, 2, OverflowPolicy::default()),
15554 Timedelta::NAT
15555 );
15556
15557 let max = Scalar::Timedelta64(i64::MAX);
15559 let soft = nancumsum_with_policy(&[max.clone(), max.clone()], OverflowPolicy::SurfaceNat);
15560 assert!(soft[1].is_missing(), "non-STRICT cumsum must NaT, not wrap");
15561 assert_eq!(soft, super::nancumsum(&[max.clone(), max]));
15562
15563 overflow_audit::enable();
15566 let _ = Timedelta::mul_scalar_with_policy(i64::MAX, 2, OverflowPolicy::HardenedNat);
15567 assert_eq!(
15568 overflow_audit::drain().len(),
15569 1,
15570 "HARDENED must record the recovery it performed"
15571 );
15572 overflow_audit::disable();
15573 }
15574
15575 #[test]
15578 fn datetime64_mixed_input_still_falls_back_axhhk() {
15579 let vals = vec![Scalar::Datetime64(DT_2020), Scalar::Int64(5)];
15580 assert!(super::nanmin(&vals).is_missing());
15591 assert_eq!(super::nanptp(&vals), Scalar::Float64(0.0));
15592 }
15593
15594 #[test]
15595 fn nansum_nanmean_mixed_timedelta_other_falls_back_620mj() {
15596 let vals = vec![Scalar::Timedelta64(3600 * 1_000_000_000), Scalar::Int64(5)];
15600 assert_eq!(super::nansum(&vals), Scalar::Float64(5.0));
15602 }
15603
15604 #[test]
15605 fn nancount_counts_non_missing() {
15606 let vals = vec![
15607 Scalar::Int64(1),
15608 Scalar::Null(NullKind::Null),
15609 Scalar::Float64(3.0),
15610 ];
15611 assert_eq!(super::nancount(&vals), Scalar::Int64(2));
15612 }
15613
15614 #[test]
15615 fn nanany_nanall_nancount_match_scalar_oracle_zr2qg() {
15616 fn next(seed: &mut u64) -> u64 {
15619 *seed = seed
15620 .wrapping_mul(6364136223846793005)
15621 .wrapping_add(1442695040888963407);
15622 *seed
15623 }
15624
15625 fn truthy(value: &Scalar) -> Option<bool> {
15626 if value.is_missing() {
15627 return None;
15628 }
15629 match value {
15630 Scalar::Bool(value) => Some(*value),
15631 Scalar::Int64(value) => Some(*value != 0),
15632 Scalar::Float64(value) => Some(*value != 0.0),
15633 Scalar::Utf8(value) => Some(!value.is_empty()),
15634 Scalar::Timedelta64(value) => Some(*value != 0),
15635 _ => None,
15636 }
15637 }
15638
15639 fn assert_nanops(case: usize, values: &[Scalar]) {
15640 let truth_values = values.iter().filter_map(truthy).collect::<Vec<_>>();
15641 let expected_any = truth_values.iter().any(|value| *value);
15642 let expected_all = !truth_values.iter().any(|value| !*value);
15643 let expected_count = values.iter().filter(|value| !value.is_missing()).count() as i64;
15644
15645 assert_eq!(
15646 super::nanany(values),
15647 Scalar::Bool(expected_any),
15648 "case={case}: nanany mismatch for {values:?}"
15649 );
15650 assert_eq!(
15651 super::nanall(values),
15652 Scalar::Bool(expected_all),
15653 "case={case}: nanall mismatch for {values:?}"
15654 );
15655 assert_eq!(
15656 super::nancount(values),
15657 Scalar::Int64(expected_count),
15658 "case={case}: nancount mismatch for {values:?}"
15659 );
15660 }
15661
15662 assert_nanops(
15663 usize::MAX,
15664 &[
15665 Scalar::Null(NullKind::Null),
15666 Scalar::Null(NullKind::NaN),
15667 Scalar::Float64(f64::NAN),
15668 Scalar::Timedelta64(i64::MIN),
15669 ],
15670 );
15671
15672 let mut seed = 0x7a20_2f7e_5ca1_ab1e_u64;
15673 for case in 0..320 {
15674 let len = (next(&mut seed) % 89 + 1) as usize;
15675 let mut values = Vec::with_capacity(len);
15676 for pos in 0..len {
15677 let raw = (next(&mut seed) % 10_001) as i64 - 5_000;
15678 let value = match next(&mut seed) % 12 {
15679 0 => Scalar::Null(NullKind::Null),
15680 1 => Scalar::Null(NullKind::NaN),
15681 2 => Scalar::Float64(f64::NAN),
15682 3 => Scalar::Bool(raw & 1 == 0),
15683 4 => Scalar::Bool(false),
15684 5 => Scalar::Int64(raw % 17),
15685 6 => Scalar::Int64(0),
15686 7 => Scalar::Float64(raw as f64 / 23.0),
15687 8 => Scalar::Float64(0.0),
15688 9 => Scalar::Utf8(if raw & 1 == 0 {
15689 String::new()
15690 } else {
15691 format!("nanops_{case}_{pos}")
15692 }),
15693 10 => Scalar::Timedelta64(raw),
15694 _ => Scalar::Timedelta64(0),
15695 };
15696 values.push(value);
15697 }
15698 assert_nanops(case, &values);
15699 }
15700 }
15701
15702 #[test]
15703 fn nanmin_basic() {
15704 let vals = vec![
15705 Scalar::Float64(5.0),
15706 Scalar::Null(NullKind::Null),
15707 Scalar::Float64(2.0),
15708 Scalar::Float64(8.0),
15709 ];
15710 assert_eq!(super::nanmin(&vals), Scalar::Float64(2.0));
15711 }
15712
15713 #[test]
15714 fn nanmax_basic() {
15715 let vals = vec![
15716 Scalar::Float64(5.0),
15717 Scalar::Float64(f64::NAN),
15718 Scalar::Float64(8.0),
15719 ];
15720 assert_eq!(super::nanmax(&vals), Scalar::Float64(8.0));
15721 }
15722
15723 #[test]
15724 fn nanmin_nanmax_empty_returns_nan() {
15725 assert!(super::nanmin(&[]).is_missing());
15726 assert!(super::nanmax(&[]).is_missing());
15727 }
15728
15729 #[test]
15730 fn nanmin_nanmax_match_same_family_oracle_vj7ds() {
15731 fn next(seed: &mut u64) -> u64 {
15734 *seed = seed
15735 .wrapping_mul(6364136223846793005)
15736 .wrapping_add(1442695040888963407);
15737 *seed
15738 }
15739
15740 fn family_cmp(left: &Scalar, right: &Scalar) -> std::cmp::Ordering {
15741 match (left, right) {
15742 (Scalar::Bool(left), Scalar::Bool(right)) => left.cmp(right),
15743 (Scalar::Int64(left), Scalar::Int64(right)) => left.cmp(right),
15744 (Scalar::Float64(left), Scalar::Float64(right)) => {
15745 left.partial_cmp(right).expect("finite floats")
15746 }
15747 (Scalar::Utf8(left), Scalar::Utf8(right)) => left.cmp(right),
15748 (Scalar::Timedelta64(left), Scalar::Timedelta64(right)) => left.cmp(right),
15749 _ => std::cmp::Ordering::Equal,
15752 }
15753 }
15754
15755 fn assert_minmax(case: usize, family: &str, values: &[Scalar]) {
15756 let present = values
15757 .iter()
15758 .filter(|value| !value.is_missing())
15759 .cloned()
15760 .collect::<Vec<_>>();
15761 let actual_min = super::nanmin(values);
15762 let actual_max = super::nanmax(values);
15763 if present.is_empty() {
15764 assert!(
15765 actual_min.is_missing(),
15766 "case={case} family={family}: expected missing min for {values:?}, got {actual_min:?}"
15767 );
15768 assert!(
15769 actual_max.is_missing(),
15770 "case={case} family={family}: expected missing max for {values:?}, got {actual_max:?}"
15771 );
15772 return;
15773 }
15774
15775 let is_expected_family = |value: &Scalar| match family {
15776 "int" => matches!(value, Scalar::Int64(_)),
15777 "float" => matches!(value, Scalar::Float64(_)),
15778 "bool" => matches!(value, Scalar::Bool(_)),
15779 "utf8" => matches!(value, Scalar::Utf8(_)),
15780 "timedelta" => matches!(value, Scalar::Timedelta64(_)),
15781 _ => false,
15782 };
15783 assert!(
15784 present.iter().all(is_expected_family),
15785 "case={case} family={family}: mixed family escaped generator: {values:?}"
15786 );
15787
15788 let expected_min = present.iter().min_by(|left, right| family_cmp(left, right));
15789 let expected_max = present.iter().max_by(|left, right| family_cmp(left, right));
15790 assert!(
15791 actual_min.semantic_eq(expected_min.expect("min")),
15792 "case={case} family={family}: expected min {:?}, got {actual_min:?} for {values:?}",
15793 expected_min.expect("min")
15794 );
15795 assert!(
15796 actual_max.semantic_eq(expected_max.expect("max")),
15797 "case={case} family={family}: expected max {:?}, got {actual_max:?} for {values:?}",
15798 expected_max.expect("max")
15799 );
15800 }
15801
15802 let all_missing = [
15803 Scalar::Null(NullKind::Null),
15804 Scalar::Null(NullKind::NaN),
15805 Scalar::Float64(f64::NAN),
15806 Scalar::Timedelta64(i64::MIN),
15807 ];
15808 assert_minmax(usize::MAX, "all_missing", &all_missing);
15809
15810 let mut seed = 0xa11c_0aba_2e7d_f00d_u64;
15811 for case in 0..240 {
15812 let len = (next(&mut seed) % 73 + 1) as usize;
15813
15814 let mut ints = Vec::with_capacity(len);
15815 ints.push(Scalar::Int64(case as i64 - 120));
15816 for _ in 1..len {
15817 let raw = (next(&mut seed) % 1_001) as i64 - 500;
15818 ints.push(match next(&mut seed) % 6 {
15819 0 => Scalar::Null(NullKind::Null),
15820 1 => Scalar::Null(NullKind::NaN),
15821 _ => Scalar::Int64(raw),
15822 });
15823 }
15824 assert_minmax(case, "int", &ints);
15825
15826 let mut floats = Vec::with_capacity(len);
15827 floats.push(Scalar::Float64(case as f64 / 11.0));
15828 for _ in 1..len {
15829 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
15830 floats.push(match next(&mut seed) % 8 {
15831 0 | 1 => Scalar::Float64(f64::NAN),
15832 2 => Scalar::Float64(f64::INFINITY),
15833 3 => Scalar::Float64(f64::NEG_INFINITY),
15834 4 => Scalar::Float64(0.0),
15835 5 => Scalar::Float64(-0.0),
15836 _ => Scalar::Float64(raw as f64 / 41.0),
15837 });
15838 }
15839 assert_minmax(case, "float", &floats);
15840
15841 let mut bools = Vec::with_capacity(len);
15842 bools.push(Scalar::Bool(case & 1 == 0));
15843 for _ in 1..len {
15844 bools.push(match next(&mut seed) % 5 {
15845 0 => Scalar::Null(NullKind::Null),
15846 1 => Scalar::Null(NullKind::NaN),
15847 raw => Scalar::Bool(raw & 1 == 0),
15848 });
15849 }
15850 assert_minmax(case, "bool", &bools);
15851
15852 let mut utf8 = Vec::with_capacity(len);
15853 utf8.push(Scalar::Utf8(format!("minmax_{}", case % 17)));
15854 for pos in 1..len {
15855 utf8.push(match next(&mut seed) % 7 {
15856 0 => Scalar::Null(NullKind::Null),
15857 1 => Scalar::Null(NullKind::NaN),
15858 raw => Scalar::Utf8(format!("minmax_{}_{}", raw, pos % 11)),
15859 });
15860 }
15861 assert_minmax(case, "utf8", &utf8);
15862
15863 let mut timedeltas = Vec::with_capacity(len);
15864 timedeltas.push(Scalar::Timedelta64(case as i64 - 120));
15865 for _ in 1..len {
15866 let raw = (next(&mut seed) % 1_003) as i64 - 501;
15867 timedeltas.push(match next(&mut seed) % 7 {
15868 0 => Scalar::Null(NullKind::Null),
15869 1 => Scalar::Timedelta64(i64::MIN),
15870 _ => Scalar::Timedelta64(raw),
15871 });
15872 }
15873 assert_minmax(case, "timedelta", &timedeltas);
15874 }
15875 }
15876
15877 #[test]
15878 fn nanmin_nanmax_mixed_incompatible_types_returns_nan() {
15879 let vals = vec![Scalar::Int64(5), Scalar::Utf8("hello".into())];
15880 assert!(super::nanmin(&vals).is_missing());
15881 assert!(super::nanmax(&vals).is_missing());
15882
15883 let vals2 = vec![Scalar::Utf8("a".into()), Scalar::Float64(3.0)];
15884 assert!(super::nanmin(&vals2).is_missing());
15885 assert!(super::nanmax(&vals2).is_missing());
15886 }
15887
15888 #[test]
15889 fn nanmin_nanmax_compatible_numeric_types_ok() {
15890 let vals = vec![Scalar::Int64(5), Scalar::Float64(3.0), Scalar::Bool(true)];
15891 assert_eq!(super::nanmin(&vals), Scalar::Bool(true));
15892 assert_eq!(super::nanmax(&vals), Scalar::Int64(5));
15893 }
15894
15895 #[test]
15896 fn nanmin_nanmax_timedelta64_returns_timedelta_yic5m() {
15897 let one_hour = 3_600 * 1_000_000_000_i64;
15901 let vals = vec![
15902 Scalar::Timedelta64(3 * one_hour),
15903 Scalar::Timedelta64(one_hour),
15904 Scalar::Timedelta64(2 * one_hour),
15905 ];
15906 assert_eq!(super::nanmin(&vals), Scalar::Timedelta64(one_hour));
15907 assert_eq!(super::nanmax(&vals), Scalar::Timedelta64(3 * one_hour));
15908 }
15909
15910 #[test]
15911 fn nanmin_nanmax_timedelta64_skips_nat_yic5m() {
15912 let one_hour = 3_600 * 1_000_000_000_i64;
15913 let vals = vec![
15914 Scalar::Timedelta64(Timedelta::NAT),
15915 Scalar::Timedelta64(one_hour),
15916 Scalar::Timedelta64(2 * one_hour),
15917 Scalar::Timedelta64(Timedelta::NAT),
15918 ];
15919 assert_eq!(super::nanmin(&vals), Scalar::Timedelta64(one_hour));
15920 assert_eq!(super::nanmax(&vals), Scalar::Timedelta64(2 * one_hour));
15921 }
15922
15923 #[test]
15924 fn nanmedian_odd_count() {
15925 let vals = vec![
15926 Scalar::Float64(3.0),
15927 Scalar::Null(NullKind::Null),
15928 Scalar::Float64(1.0),
15929 Scalar::Float64(2.0),
15930 ];
15931 assert_eq!(super::nanmedian(&vals), Scalar::Float64(2.0));
15932 }
15933
15934 #[test]
15935 fn nanmedian_even_count() {
15936 let vals = vec![
15937 Scalar::Float64(1.0),
15938 Scalar::Float64(3.0),
15939 Scalar::Float64(2.0),
15940 Scalar::Float64(4.0),
15941 ];
15942 assert_eq!(super::nanmedian(&vals), Scalar::Float64(2.5));
15943 }
15944
15945 #[test]
15946 fn nanmedian_matches_numeric_and_timedelta_oracle_oabhi() {
15947 fn next(seed: &mut u64) -> u64 {
15950 *seed = seed
15951 .wrapping_mul(6364136223846793005)
15952 .wrapping_add(1442695040888963407);
15953 *seed
15954 }
15955
15956 fn expected_numeric(values: &[Scalar]) -> Scalar {
15957 let mut finite = values
15958 .iter()
15959 .filter(|value| !value.is_missing())
15960 .filter_map(|value| value.to_f64().ok())
15961 .filter(|value| !value.is_nan())
15962 .collect::<Vec<_>>();
15963 if finite.is_empty() {
15964 return Scalar::Null(NullKind::NaN);
15965 }
15966 finite.sort_by(|left, right| left.partial_cmp(right).expect("finite values"));
15967 let mid = finite.len() / 2;
15968 if finite.len().is_multiple_of(2) {
15969 Scalar::Float64((finite[mid - 1] + finite[mid]) / 2.0)
15970 } else {
15971 Scalar::Float64(finite[mid])
15972 }
15973 }
15974
15975 fn expected_timedelta(values: &[Scalar]) -> Scalar {
15976 let mut finite = values
15977 .iter()
15978 .filter_map(|value| match value {
15979 Scalar::Timedelta64(ns) if !value.is_missing() => Some(*ns),
15980 _ => None,
15981 })
15982 .collect::<Vec<_>>();
15983 if finite.is_empty() {
15984 return Scalar::Null(NullKind::NaN);
15985 }
15986 finite.sort_unstable();
15987 let mid = finite.len() / 2;
15988 let median = if finite.len().is_multiple_of(2) {
15989 (i128::from(finite[mid - 1]) + i128::from(finite[mid])) / 2
15990 } else {
15991 i128::from(finite[mid])
15992 };
15993 Scalar::Timedelta64(median as i64)
15994 }
15995
15996 fn assert_median(case: usize, family: &str, values: &[Scalar], expected: Scalar) {
15997 let actual = super::nanmedian(values);
15998 assert!(
15999 actual.semantic_eq(&expected),
16000 "case={case} family={family}: expected {expected:?}, got {actual:?} for {values:?}"
16001 );
16002 }
16003
16004 assert_median(
16005 usize::MAX,
16006 "numeric_all_missing",
16007 &[Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)],
16008 Scalar::Null(NullKind::NaN),
16009 );
16010 assert_median(
16011 usize::MAX - 1,
16012 "timedelta_all_missing",
16013 &[Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)],
16014 Scalar::Null(NullKind::NaN),
16015 );
16016 let beyond_f64_exact_ns = 200 * Timedelta::NANOS_PER_DAY;
16017 assert_median(
16018 usize::MAX - 2,
16019 "timedelta_odd_median_beyond_f64_exactness",
16020 &[
16021 Scalar::Timedelta64(beyond_f64_exact_ns),
16022 Scalar::Timedelta64(beyond_f64_exact_ns + 1),
16023 Scalar::Timedelta64(beyond_f64_exact_ns + 2),
16024 Scalar::Timedelta64(Timedelta::NAT),
16025 ],
16026 Scalar::Timedelta64(beyond_f64_exact_ns + 1),
16027 );
16028
16029 let mut seed = 0x0ab1_1eda_57a7_15e5_u64;
16030 for case in 0..220 {
16031 let len = (next(&mut seed) % 79 + 1) as usize;
16032
16033 let mut numeric = Vec::with_capacity(len);
16034 numeric.push(Scalar::Int64(case as i64 - 110));
16035 for _ in 1..len {
16036 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16037 numeric.push(match next(&mut seed) % 8 {
16038 0 => Scalar::Null(NullKind::Null),
16039 1 => Scalar::Null(NullKind::NaN),
16040 2 => Scalar::Float64(f64::NAN),
16041 3 => Scalar::Bool(raw & 1 == 0),
16042 4 => Scalar::Int64(raw % 251),
16043 5 => Scalar::Float64(raw as f64 / 61.0),
16044 6 => Scalar::Float64(0.0),
16045 _ => Scalar::Float64(-0.0),
16046 });
16047 }
16048 assert_median(case, "numeric", &numeric, expected_numeric(&numeric));
16049
16050 let mut timedeltas = Vec::with_capacity(len);
16051 timedeltas.push(Scalar::Timedelta64(case as i64 - 110));
16052 for _ in 1..len {
16053 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16054 timedeltas.push(match next(&mut seed) % 7 {
16055 0 => Scalar::Null(NullKind::Null),
16056 1 => Scalar::Timedelta64(i64::MIN),
16057 _ => Scalar::Timedelta64(raw),
16058 });
16059 }
16060 assert_median(
16061 case,
16062 "timedelta",
16063 &timedeltas,
16064 expected_timedelta(&timedeltas),
16065 );
16066 }
16067 }
16068
16069 #[test]
16070 fn nanvar_nanstd_nansem_match_numeric_and_timedelta_oracle_k7apg() {
16071 fn next(seed: &mut u64) -> u64 {
16074 *seed = seed
16075 .wrapping_mul(2862933555777941757)
16076 .wrapping_add(3037000493);
16077 *seed
16078 }
16079
16080 fn numeric_samples(values: &[Scalar]) -> Vec<f64> {
16081 values
16082 .iter()
16083 .filter(|value| !value.is_missing())
16084 .filter_map(|value| value.to_f64().ok())
16085 .collect()
16086 }
16087
16088 fn timedelta_samples(values: &[Scalar]) -> Vec<f64> {
16089 values
16090 .iter()
16091 .filter_map(|value| match value {
16092 Scalar::Timedelta64(ns) if !value.is_missing() => Some(*ns as f64),
16093 _ => None,
16094 })
16095 .collect()
16096 }
16097
16098 fn reductions_from_samples(samples: &[f64], ddof: usize) -> Option<(f64, f64, f64)> {
16099 if samples.len() <= ddof {
16100 return None;
16101 }
16102 let mean = samples.iter().sum::<f64>() / samples.len() as f64;
16103 let sum_sq = samples
16104 .iter()
16105 .map(|value| (value - mean).powi(2))
16106 .sum::<f64>();
16107 let var = sum_sq / (samples.len() - ddof) as f64;
16108 let std = var.sqrt();
16109 let sem = std / (samples.len() as f64).sqrt();
16110 Some((var, std, sem))
16111 }
16112
16113 fn expected_numeric(values: &[Scalar], ddof: usize) -> (Scalar, Scalar, Scalar) {
16114 let samples = numeric_samples(values);
16115 let Some((var, std, sem)) = reductions_from_samples(&samples, ddof) else {
16116 let missing = Scalar::Null(NullKind::NaN);
16117 return (missing.clone(), missing.clone(), missing);
16118 };
16119 (
16120 Scalar::Float64(var),
16121 Scalar::Float64(std),
16122 Scalar::Float64(sem),
16123 )
16124 }
16125
16126 fn expected_timedelta(values: &[Scalar], ddof: usize) -> (Scalar, Scalar, Scalar) {
16127 let samples = timedelta_samples(values);
16128 if samples.is_empty() {
16129 let missing = Scalar::Timedelta64(Timedelta::NAT);
16130 return (missing.clone(), missing.clone(), missing);
16131 }
16132 let Some((var, std, sem)) = reductions_from_samples(&samples, ddof) else {
16133 let missing = Scalar::Timedelta64(i64::MIN);
16134 return (missing.clone(), missing.clone(), missing);
16135 };
16136 (
16137 Scalar::Timedelta64(var as i64),
16138 Scalar::Timedelta64(std as i64),
16139 Scalar::Timedelta64(sem as i64),
16140 )
16141 }
16142
16143 fn assert_reductions(
16144 case: usize,
16145 family: &str,
16146 values: &[Scalar],
16147 ddof: usize,
16148 expected: (Scalar, Scalar, Scalar),
16149 ) {
16150 let (expected_var, expected_std, expected_sem) = expected;
16151 let actual_var = super::nanvar(values, ddof);
16152 let actual_std = super::nanstd(values, ddof);
16153 let actual_sem = super::nansem(values, ddof);
16154 assert!(
16155 actual_var.semantic_eq(&expected_var),
16156 "case={case} family={family} ddof={ddof}: expected var {expected_var:?}, got {actual_var:?} for {values:?}"
16157 );
16158 assert!(
16159 actual_std.semantic_eq(&expected_std),
16160 "case={case} family={family} ddof={ddof}: expected std {expected_std:?}, got {actual_std:?} for {values:?}"
16161 );
16162 assert!(
16163 actual_sem.semantic_eq(&expected_sem),
16164 "case={case} family={family} ddof={ddof}: expected sem {expected_sem:?}, got {actual_sem:?} for {values:?}"
16165 );
16166 }
16167
16168 let numeric_all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
16169 assert_reductions(
16170 usize::MAX,
16171 "numeric_all_missing",
16172 &numeric_all_missing,
16173 0,
16174 expected_numeric(&numeric_all_missing, 0),
16175 );
16176
16177 let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
16178 assert_reductions(
16179 usize::MAX - 1,
16180 "timedelta_all_missing",
16181 &td_all_missing,
16182 0,
16183 expected_timedelta(&td_all_missing, 0),
16184 );
16185
16186 let mut seed = 0x7a11_c0de_5eed_0421_u64;
16187 for case in 0..240 {
16188 let len = (next(&mut seed) % 83 + 1) as usize;
16189 let ddof = (next(&mut seed) % 4) as usize;
16190
16191 let mut numeric = Vec::with_capacity(len);
16192 numeric.push(Scalar::Float64(case as f64 / 13.0));
16193 for _ in 1..len {
16194 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16195 numeric.push(match next(&mut seed) % 8 {
16196 0 => Scalar::Null(NullKind::Null),
16197 1 => Scalar::Null(NullKind::NaN),
16198 2 => Scalar::Float64(f64::NAN),
16199 3 => Scalar::Bool(raw & 1 == 0),
16200 4 => Scalar::Int64(raw % 251),
16201 5 => Scalar::Float64(raw as f64 / 73.0),
16202 6 => Scalar::Float64(0.0),
16203 _ => Scalar::Float64(-0.0),
16204 });
16205 }
16206 assert_reductions(
16207 case,
16208 "numeric",
16209 &numeric,
16210 ddof,
16211 expected_numeric(&numeric, ddof),
16212 );
16213
16214 let mut timedeltas = Vec::with_capacity(len);
16215 timedeltas.push(Scalar::Timedelta64(case as i64 - 120));
16216 for _ in 1..len {
16217 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16218 timedeltas.push(match next(&mut seed) % 7 {
16219 0 => Scalar::Null(NullKind::Null),
16220 1 => Scalar::Timedelta64(i64::MIN),
16221 _ => Scalar::Timedelta64(raw),
16222 });
16223 }
16224 assert_reductions(
16225 case,
16226 "timedelta",
16227 &timedeltas,
16228 ddof,
16229 expected_timedelta(&timedeltas, ddof),
16230 );
16231 }
16232 }
16233
16234 #[test]
16235 fn nanvar_population() {
16236 let vals = vec![
16237 Scalar::Float64(2.0),
16238 Scalar::Float64(4.0),
16239 Scalar::Float64(4.0),
16240 Scalar::Float64(4.0),
16241 Scalar::Float64(5.0),
16242 Scalar::Float64(5.0),
16243 Scalar::Float64(7.0),
16244 Scalar::Float64(9.0),
16245 ];
16246 let var = super::nanvar(&vals, 0);
16247 assert!(matches!(var, Scalar::Float64(_)), "expected Float64");
16248 if let Scalar::Float64(v) = var {
16249 assert!((v - 4.0).abs() < 1e-10);
16250 }
16251 }
16252
16253 #[test]
16254 fn nanvar_sample_ddof1() {
16255 let vals = vec![
16256 Scalar::Float64(2.0),
16257 Scalar::Float64(4.0),
16258 Scalar::Float64(4.0),
16259 Scalar::Float64(4.0),
16260 Scalar::Float64(5.0),
16261 Scalar::Float64(5.0),
16262 Scalar::Float64(7.0),
16263 Scalar::Float64(9.0),
16264 ];
16265 let var = super::nanvar(&vals, 1);
16266 assert!(matches!(var, Scalar::Float64(_)), "expected Float64");
16267 if let Scalar::Float64(v) = var {
16268 assert!((v - 32.0 / 7.0).abs() < 1e-10);
16269 }
16270 }
16271
16272 #[test]
16273 fn nanvar_insufficient_values_returns_nan() {
16274 let vals = vec![Scalar::Float64(5.0)];
16275 assert!(super::nanvar(&vals, 1).is_missing());
16276 }
16277
16278 #[test]
16279 fn nanstd_is_sqrt_of_var() {
16280 let vals = vec![
16281 Scalar::Float64(2.0),
16282 Scalar::Float64(4.0),
16283 Scalar::Float64(4.0),
16284 Scalar::Float64(4.0),
16285 Scalar::Float64(5.0),
16286 Scalar::Float64(5.0),
16287 Scalar::Float64(7.0),
16288 Scalar::Float64(9.0),
16289 ];
16290 let std = super::nanstd(&vals, 0);
16291 assert!(matches!(std, Scalar::Float64(_)), "expected Float64");
16292 if let Scalar::Float64(v) = std {
16293 assert!((v - 2.0).abs() < 1e-10);
16294 }
16295 }
16296
16297 #[test]
16298 fn nanmedian_timedelta64_preserves_dtype_j8ntk() {
16299 let one_hour = 3_600 * 1_000_000_000_i64;
16302 let vals = vec![
16303 Scalar::Timedelta64(one_hour),
16304 Scalar::Timedelta64(2 * one_hour),
16305 Scalar::Timedelta64(3 * one_hour),
16306 ];
16307 assert_eq!(super::nanmedian(&vals), Scalar::Timedelta64(2 * one_hour));
16308 }
16309
16310 #[test]
16311 fn nanstd_timedelta64_preserves_dtype_j8ntk() {
16312 let one_hour: i64 = 3_600 * 1_000_000_000;
16316 let vals = vec![
16317 Scalar::Timedelta64(one_hour),
16318 Scalar::Timedelta64(2 * one_hour),
16319 Scalar::Timedelta64(3 * one_hour),
16320 ];
16321 let std = super::nanstd(&vals, 0);
16322 assert!(matches!(std, Scalar::Timedelta64(_)));
16323 if let Scalar::Timedelta64(ns) = std {
16324 let expected = (2.0_f64 / 3.0).sqrt() * one_hour as f64;
16325 assert!(
16326 (ns as f64 - expected).abs() < 1e6,
16327 "expected ~{expected} ns, got {ns}"
16328 );
16329 }
16330 }
16331
16332 #[test]
16333 fn nanstd_nansem_timedelta64_insufficient_returns_nat_j8ntk() {
16334 let one_hour = 3_600 * 1_000_000_000_i64;
16335 let vals = vec![Scalar::Timedelta64(one_hour)];
16336 assert_eq!(super::nanstd(&vals, 1), Scalar::Timedelta64(Timedelta::NAT));
16338 assert_eq!(super::nansem(&vals, 1), Scalar::Timedelta64(Timedelta::NAT));
16339 }
16340
16341 #[test]
16342 fn nanops_with_mixed_types() {
16343 let vals = vec![
16344 Scalar::Bool(true),
16345 Scalar::Int64(3),
16346 Scalar::Float64(6.0),
16347 Scalar::Null(NullKind::Null),
16348 ];
16349 assert_eq!(super::nansum(&vals), Scalar::Float64(10.0));
16350 assert_eq!(super::nancount(&vals), Scalar::Int64(3));
16351 }
16352
16353 #[test]
16354 fn nanops_all_missing_returns_identity() {
16355 let vals = vec![Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
16356 assert_eq!(super::nansum(&vals), Scalar::Float64(0.0));
16357 assert!(super::nanmean(&vals).is_missing());
16358 assert!(super::nanmedian(&vals).is_missing());
16359 assert!(super::nanvar(&vals, 0).is_missing());
16360 assert!(super::nanstd(&vals, 0).is_missing());
16361 }
16362
16363 #[test]
16366 fn timedelta_parse_simple_units() {
16367 use super::Timedelta;
16368 assert_eq!(Timedelta::parse("1d").unwrap(), Timedelta::NANOS_PER_DAY);
16369 assert_eq!(
16370 Timedelta::parse("2h").unwrap(),
16371 2 * Timedelta::NANOS_PER_HOUR
16372 );
16373 assert_eq!(
16374 Timedelta::parse("30m").unwrap(),
16375 30 * Timedelta::NANOS_PER_MIN
16376 );
16377 assert_eq!(
16378 Timedelta::parse("45s").unwrap(),
16379 45 * Timedelta::NANOS_PER_SEC
16380 );
16381 assert_eq!(
16382 Timedelta::parse("100ms").unwrap(),
16383 100 * Timedelta::NANOS_PER_MILLI
16384 );
16385 assert_eq!(
16386 Timedelta::parse("500us").unwrap(),
16387 500 * Timedelta::NANOS_PER_MICRO
16388 );
16389 assert_eq!(Timedelta::parse("1000ns").unwrap(), 1000);
16390 }
16391
16392 #[test]
16393 fn timedelta_parse_zero_valued_compound() {
16394 use super::Timedelta;
16395 for s in [
16402 "0 seconds",
16403 "0 second",
16404 "0 sec",
16405 "0s",
16406 "0 days",
16407 "0d",
16408 "0 hours",
16409 "0.0 hours",
16410 "0 minutes",
16411 "0ms",
16412 "0us",
16413 "0ns",
16414 "0",
16415 "0 days 0 seconds",
16416 ] {
16417 assert_eq!(Timedelta::parse(s).unwrap(), 0, "parse({s:?}) should be 0");
16418 }
16419 assert_eq!(Timedelta::parse("-0 seconds").unwrap(), 0);
16421 assert!(Timedelta::parse("0 fortnights").is_err());
16424 assert!(Timedelta::parse("seconds").is_err());
16425 }
16426
16427 #[test]
16428 fn timedelta_parse_compound() {
16429 use super::Timedelta;
16430 let expected = Timedelta::NANOS_PER_DAY
16431 + 2 * Timedelta::NANOS_PER_HOUR
16432 + 30 * Timedelta::NANOS_PER_MIN;
16433 assert_eq!(Timedelta::parse("1d 2h 30m").unwrap(), expected);
16434 assert_eq!(Timedelta::parse("1d2h30m").unwrap(), expected);
16435 }
16436
16437 #[test]
16438 fn timedelta_parse_leading_sign_spares_the_clock_part() {
16439 use super::Timedelta;
16440 const S: i64 = Timedelta::NANOS_PER_SEC;
16441 assert_eq!(Timedelta::parse("-1 days 02:03:04").unwrap(), -79_016 * S);
16444 assert_eq!(Timedelta::parse("-1 days +02:03:04").unwrap(), -79_016 * S);
16445 assert_eq!(
16446 Timedelta::parse("-3 days +23:59:59.5").unwrap(),
16447 -172_800 * S - S / 2
16448 );
16449 assert_eq!(Timedelta::parse("-0 days 01:00:00").unwrap(), 3_600 * S);
16450 assert_eq!(Timedelta::parse("-1d2h").unwrap(), -93_600 * S);
16452 assert_eq!(Timedelta::parse("-02:03:04").unwrap(), -7_384 * S);
16453 assert!(Timedelta::parse("-1 days -02:03:04").is_err());
16455 assert!(Timedelta::parse("1 days -02:00:00").is_err());
16456 }
16457
16458 #[test]
16459 fn timedelta_parse_iso8601_matches_pandas_tdiso() {
16460 use super::Timedelta;
16461 assert_eq!(Timedelta::parse("P1DT2H3M4S").unwrap(), 93_784_000_000_000);
16463 assert_eq!(Timedelta::parse("PT1H").unwrap(), 3_600_000_000_000);
16464 assert_eq!(Timedelta::parse("PT1H30M").unwrap(), 5_400_000_000_000);
16465 assert_eq!(Timedelta::parse("P1D").unwrap(), 86_400_000_000_000);
16466 assert_eq!(Timedelta::parse("P2W").unwrap(), 1_209_600_000_000_000);
16467 assert_eq!(Timedelta::parse("PT0.5S").unwrap(), 500_000_000);
16468 assert_eq!(Timedelta::parse("P1M").unwrap(), 60_000_000_000);
16470 assert_eq!(Timedelta::parse("P1H").unwrap(), 3_600_000_000_000);
16471 assert_eq!(Timedelta::parse("PT1D").unwrap(), 86_400_000_000_000);
16472 assert_eq!(Timedelta::parse("P1D1H").unwrap(), 90_000_000_000_000);
16473 assert_eq!(Timedelta::parse("-P1DT2H").unwrap(), -93_600_000_000_000);
16474 assert!(Timedelta::parse("P1Y").is_err());
16476 assert!(Timedelta::parse("p1d").is_err());
16477 assert!(Timedelta::parse("P").is_err());
16478 assert!(Timedelta::parse("PT").is_err());
16479 }
16480
16481 #[test]
16482 fn timedelta_parse_time_format() {
16483 use super::Timedelta;
16484 let expected = Timedelta::NANOS_PER_HOUR
16485 + 30 * Timedelta::NANOS_PER_MIN
16486 + 45 * Timedelta::NANOS_PER_SEC;
16487 assert_eq!(Timedelta::parse("01:30:45").unwrap(), expected);
16488 }
16489
16490 #[test]
16491 fn timedelta_parse_time_fraction_rejects_unicode_without_panic() {
16492 use super::{Timedelta, TimedeltaError};
16493 let err = Timedelta::parse("00:00:00.\u{00e9}\u{00e9}\u{00e9}\u{00e9}\u{00e9}")
16494 .expect_err("non-ASCII fractional seconds must reject");
16495 assert!(matches!(err, TimedeltaError::InvalidFormat(_)));
16496 }
16497
16498 #[test]
16499 fn timedelta_parse_time_format_rejects_overflow_without_panic() {
16500 use super::{Timedelta, TimedeltaError};
16501 let err = Timedelta::parse("9223372036854775807:00")
16502 .expect_err("oversized hour component must reject");
16503 assert!(matches!(err, TimedeltaError::InvalidFormat(_)));
16504 }
16505
16506 #[test]
16507 fn timedelta_parse_rejects_huge_value_overflow_zw3mg() {
16508 use super::{Timedelta, TimedeltaError};
16515 let huge = format!("{} days", "9".repeat(18));
16516 assert!(matches!(
16517 Timedelta::parse(&huge).expect_err("9...(18 9s) days must overflow"),
16518 TimedeltaError::Overflow
16519 ));
16520 }
16521
16522 #[test]
16523 fn timedelta_parse_nat() {
16524 use super::Timedelta;
16525 assert_eq!(Timedelta::parse("NaT").unwrap(), Timedelta::NAT);
16526 assert_eq!(Timedelta::parse("nat").unwrap(), Timedelta::NAT);
16527 }
16528
16529 #[test]
16530 fn timedelta_parse_negative() {
16531 use super::Timedelta;
16532 assert_eq!(Timedelta::parse("-1d").unwrap(), -Timedelta::NANOS_PER_DAY);
16533 }
16534
16535 #[test]
16536 fn timedelta_components() {
16537 use super::Timedelta;
16538 let nanos = Timedelta::NANOS_PER_DAY
16539 + Timedelta::NANOS_PER_HOUR
16540 + Timedelta::NANOS_PER_MIN
16541 + Timedelta::NANOS_PER_SEC
16542 + Timedelta::NANOS_PER_MILLI
16543 + 2 * Timedelta::NANOS_PER_MICRO
16544 + 3;
16545 let comp = Timedelta::components(nanos);
16546 assert_eq!(comp.days, 1);
16547 assert_eq!(comp.hours, 1);
16548 assert_eq!(comp.minutes, 1);
16549 assert_eq!(comp.seconds, 1);
16550 assert_eq!(comp.milliseconds, 1);
16551 assert_eq!(comp.microseconds, 2);
16552 assert_eq!(comp.nanoseconds, 3);
16553 }
16554
16555 #[test]
16556 fn timedelta_negative_components_floor_div() {
16557 use super::Timedelta;
16558 let neg_1s = -Timedelta::NANOS_PER_SEC;
16561 assert_eq!(Timedelta::days(neg_1s), Some(-1));
16562 assert_eq!(Timedelta::seconds(neg_1s), Some(86399));
16563 assert_eq!(Timedelta::microseconds(neg_1s), Some(0));
16564 assert_eq!(Timedelta::nanoseconds(neg_1s), Some(0));
16565 let comp = Timedelta::components(neg_1s);
16566 assert_eq!(
16567 (
16568 comp.days,
16569 comp.hours,
16570 comp.minutes,
16571 comp.seconds,
16572 comp.milliseconds,
16573 comp.microseconds,
16574 comp.nanoseconds
16575 ),
16576 (-1, 23, 59, 59, 0, 0, 0)
16577 );
16578
16579 let neg = -86_401 * Timedelta::NANOS_PER_SEC;
16581 assert_eq!(Timedelta::days(neg), Some(-2));
16582 assert_eq!(Timedelta::seconds(neg), Some(86399));
16583 }
16584
16585 #[test]
16600 fn timedelta_components_are_missing_for_nat_not_zero_406ni() {
16601 use super::Timedelta;
16602 assert_eq!(Timedelta::days(Timedelta::NAT), None);
16603 assert_eq!(Timedelta::seconds(Timedelta::NAT), None);
16604 assert_eq!(Timedelta::microseconds(Timedelta::NAT), None);
16605 assert_eq!(Timedelta::nanoseconds(Timedelta::NAT), None);
16606
16607 let one_day = Timedelta::NANOS_PER_DAY;
16612 assert_eq!(Timedelta::days(one_day), Some(1));
16613 assert_eq!(Timedelta::seconds(one_day), Some(0));
16614 assert_eq!(Timedelta::microseconds(one_day), Some(0));
16615 assert_eq!(Timedelta::nanoseconds(one_day), Some(0));
16616 }
16617
16618 #[test]
16619 fn timedelta_total_seconds() {
16620 use super::Timedelta;
16621 let nanos = 90_000_000_000i64; assert!((Timedelta::total_seconds(nanos) - 90.0).abs() < 1e-9);
16623 assert!(Timedelta::total_seconds(Timedelta::NAT).is_nan());
16624 }
16625
16626 #[test]
16627 fn timedelta_format_basic() {
16628 use super::Timedelta;
16629 assert_eq!(Timedelta::format(Timedelta::NAT), "NaT");
16630 assert_eq!(
16631 Timedelta::format(Timedelta::NANOS_PER_DAY),
16632 "1 days 00:00:00"
16633 );
16634 assert_eq!(
16635 Timedelta::format(Timedelta::NANOS_PER_DAY + 2 * Timedelta::NANOS_PER_HOUR),
16636 "1 days 02:00:00"
16637 );
16638 }
16639
16640 #[test]
16641 fn timedelta_format_subsecond_matches_pandas() {
16642 use super::Timedelta;
16643 assert_eq!(
16647 Timedelta::format(1_500_000_000), "0 days 00:00:01.500000"
16649 );
16650 assert_eq!(
16651 Timedelta::format(1_000_000), "0 days 00:00:00.001000"
16653 );
16654 assert_eq!(
16655 Timedelta::format(123_456_000), "0 days 00:00:00.123456"
16657 );
16658 assert_eq!(
16660 Timedelta::format(500), "0 days 00:00:00.000000500"
16662 );
16663 assert_eq!(Timedelta::format(123_456_789), "0 days 00:00:00.123456789");
16664 }
16665
16666 #[test]
16667 fn timedelta_format_negative_uses_python_borrow_form() {
16668 use super::Timedelta;
16669 assert_eq!(Timedelta::format(-1_000_000_000), "-1 days +23:59:59");
16673 assert_eq!(
16674 Timedelta::format(-Timedelta::NANOS_PER_DAY),
16675 "-1 days +00:00:00"
16676 );
16677 assert_eq!(
16678 Timedelta::format(-25 * Timedelta::NANOS_PER_HOUR),
16679 "-2 days +23:00:00"
16680 );
16681 assert_eq!(
16682 Timedelta::format(-1_500_000_000),
16683 "-1 days +23:59:58.500000"
16684 );
16685 assert_eq!(Timedelta::format(-500), "-1 days +23:59:59.999999500");
16686 assert_eq!(Timedelta::format(-1), "-1 days +23:59:59.999999999");
16687 }
16688
16689 #[test]
16690 #[ignore = "foreground release attribution harness"]
16691 fn timedelta_format_single_buffer_ab_5ro9h() {
16692 use std::{hint::black_box, time::Instant};
16693
16694 use super::Timedelta;
16695
16696 fn former(nanos: i64) -> String {
16697 if nanos == Timedelta::NAT {
16698 return "NaT".to_string();
16699 }
16700
16701 let days = nanos.div_euclid(Timedelta::NANOS_PER_DAY);
16702 let rem = nanos.rem_euclid(Timedelta::NANOS_PER_DAY);
16703 let hours = rem / Timedelta::NANOS_PER_HOUR;
16704 let minutes = (rem % Timedelta::NANOS_PER_HOUR) / Timedelta::NANOS_PER_MIN;
16705 let seconds = (rem % Timedelta::NANOS_PER_MIN) / Timedelta::NANOS_PER_SEC;
16706 let frac = rem % Timedelta::NANOS_PER_SEC;
16707
16708 let time_part = format!("{hours:02}:{minutes:02}:{seconds:02}");
16709 let sep = if days < 0 { "+" } else { "" };
16710 if frac > 0 {
16711 if frac % 1_000 == 0 {
16712 format!("{days} days {sep}{time_part}.{:06}", frac / 1_000)
16713 } else {
16714 format!("{days} days {sep}{time_part}.{frac:09}")
16715 }
16716 } else {
16717 format!("{days} days {sep}{time_part}")
16718 }
16719 }
16720
16721 fn candidate(nanos: i64) -> String {
16722 Timedelta::format(nanos)
16723 }
16724
16725 fn elapsed(values: &[i64], format: fn(i64) -> String) -> u128 {
16726 let started = Instant::now();
16727 let mut digest = 0_usize;
16728 for &value in values {
16729 digest = digest.wrapping_add(black_box(format(black_box(value))).len());
16730 }
16731 black_box(digest);
16732 started.elapsed().as_nanos()
16733 }
16734
16735 fn median(samples: &mut [u128]) -> u128 {
16736 samples.sort_unstable();
16737 samples[samples.len() / 2]
16738 }
16739
16740 let mut seed = 0x8f42_67a1_b3d9_c50e_u64;
16741 let values: Vec<i64> = (0..16_384)
16742 .map(|i| {
16743 seed = seed
16744 .wrapping_mul(6_364_136_223_846_793_005)
16745 .wrapping_add(1_442_695_040_888_963_407);
16746 let magnitude = (seed & i64::MAX as u64) as i64;
16747 match i % 4 {
16748 0 => magnitude - magnitude % Timedelta::NANOS_PER_SEC,
16749 1 => magnitude,
16750 2 => -(magnitude - magnitude % Timedelta::NANOS_PER_MICRO),
16751 _ => -magnitude,
16752 }
16753 })
16754 .collect();
16755
16756 for &value in &[
16757 Timedelta::NAT,
16758 0,
16759 1,
16760 -1,
16761 Timedelta::NANOS_PER_DAY,
16762 -Timedelta::NANOS_PER_DAY,
16763 i64::MAX,
16764 i64::MIN + 1,
16765 ] {
16766 assert_eq!(former(value), candidate(value));
16767 }
16768 for &value in &values {
16769 assert_eq!(former(value), candidate(value));
16770 }
16771
16772 for _ in 0..2 {
16773 black_box(elapsed(&values, former));
16774 black_box(elapsed(&values, candidate));
16775 }
16776
16777 let mut former_samples = Vec::with_capacity(18);
16778 let mut candidate_samples = Vec::with_capacity(18);
16779 for block in 0_usize..9 {
16780 if block.is_multiple_of(2) {
16781 former_samples.push(elapsed(&values, former));
16782 candidate_samples.push(elapsed(&values, candidate));
16783 candidate_samples.push(elapsed(&values, candidate));
16784 former_samples.push(elapsed(&values, former));
16785 } else {
16786 candidate_samples.push(elapsed(&values, candidate));
16787 former_samples.push(elapsed(&values, former));
16788 former_samples.push(elapsed(&values, former));
16789 candidate_samples.push(elapsed(&values, candidate));
16790 }
16791 }
16792
16793 let former_p50 = median(&mut former_samples);
16794 let candidate_p50 = median(&mut candidate_samples);
16795 eprintln!(
16796 "TIMEDELTA_FORMAT_SINGLE_BUFFER_AB rows={} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} ratio={:.6}",
16797 values.len(),
16798 former_p50 as f64 / candidate_p50 as f64,
16799 );
16800 eprintln!("TIMEDELTA_FORMAT_SINGLE_BUFFER_AB former_samples_ns={former_samples:?}");
16801 eprintln!("TIMEDELTA_FORMAT_SINGLE_BUFFER_AB candidate_samples_ns={candidate_samples:?}");
16802 }
16803
16804 #[test]
16805 fn timedelta_isoformat_basic() {
16806 use super::Timedelta;
16807 assert_eq!(Timedelta::isoformat(Timedelta::NAT), "NaT");
16808 assert_eq!(Timedelta::isoformat(0), "P0DT0H0M0S");
16809 assert_eq!(Timedelta::isoformat(Timedelta::NANOS_PER_DAY), "P1DT0H0M0S");
16810 assert_eq!(
16811 Timedelta::isoformat(
16812 Timedelta::NANOS_PER_DAY
16813 + 2 * Timedelta::NANOS_PER_HOUR
16814 + 30 * Timedelta::NANOS_PER_MIN
16815 + 45 * Timedelta::NANOS_PER_SEC
16816 ),
16817 "P1DT2H30M45S"
16818 );
16819 assert_eq!(
16820 Timedelta::isoformat(Timedelta::NANOS_PER_SEC + 500_000_000),
16821 "P0DT0H0M1.5S"
16822 );
16823 assert_eq!(
16828 Timedelta::isoformat(-(Timedelta::NANOS_PER_DAY + Timedelta::NANOS_PER_HOUR)),
16829 "P-2DT23H0M0S"
16830 );
16831 assert_eq!(Timedelta::isoformat(-1), "P-1DT23H59M59.999999999S");
16832 }
16833
16834 #[test]
16835 #[ignore = "foreground release attribution harness"]
16836 fn timedelta_isoformat_single_buffer_ab_7jra1() {
16837 use std::{hint::black_box, time::Instant};
16838
16839 use super::Timedelta;
16840
16841 fn former_impl(nanos: i64) -> String {
16842 if nanos == Timedelta::NAT {
16843 return "NaT".to_string();
16844 }
16845
16846 let negative = nanos < 0;
16847 let abs_nanos = nanos.saturating_abs();
16848 let days = abs_nanos / Timedelta::NANOS_PER_DAY;
16849 let remaining = abs_nanos % Timedelta::NANOS_PER_DAY;
16850 let hours = remaining / Timedelta::NANOS_PER_HOUR;
16851 let remaining = remaining % Timedelta::NANOS_PER_HOUR;
16852 let minutes = remaining / Timedelta::NANOS_PER_MIN;
16853 let remaining = remaining % Timedelta::NANOS_PER_MIN;
16854 let seconds = remaining / Timedelta::NANOS_PER_SEC;
16855 let sub_sec_nanos = remaining % Timedelta::NANOS_PER_SEC;
16856
16857 let mut result = String::new();
16858 if negative {
16859 result.push('-');
16860 }
16861
16862 result.push_str(&format!("P{days}DT{hours}H{minutes}M"));
16863
16864 if sub_sec_nanos == 0 {
16865 result.push_str(&format!("{seconds}S"));
16866 } else {
16867 let frac = format!("{sub_sec_nanos:09}");
16868 let trimmed = frac.trim_end_matches('0');
16869 result.push_str(&format!("{seconds}.{trimmed}S"));
16870 }
16871
16872 result
16873 }
16874
16875 fn elapsed(values: &[i64], format: impl Fn(i64) -> String) -> u128 {
16876 let start = Instant::now();
16877 let mut digest = 0_usize;
16878 for &value in values {
16879 digest = digest.wrapping_add(black_box(format(black_box(value))).len());
16880 }
16881 black_box(digest);
16882 start.elapsed().as_nanos()
16883 }
16884
16885 fn median(values: &mut [u128]) -> u128 {
16886 values.sort_unstable();
16887 values[values.len() / 2]
16888 }
16889
16890 let mut seed = 0x7d5a_4c31_91e2_b607_u64;
16891 let values: Vec<i64> = (0..16_384)
16892 .map(|i| {
16893 seed = seed
16894 .wrapping_mul(6_364_136_223_846_793_005)
16895 .wrapping_add(1_442_695_040_888_963_407);
16896 let magnitude =
16897 (seed & i64::MAX as u64) as i64 % (3_650 * Timedelta::NANOS_PER_DAY);
16898 match i % 4 {
16899 0 => magnitude - magnitude % Timedelta::NANOS_PER_SEC,
16900 1 => magnitude,
16901 2 => -(magnitude - magnitude % Timedelta::NANOS_PER_MICRO),
16902 _ => -magnitude,
16903 }
16904 })
16905 .collect();
16906
16907 for &value in &[Timedelta::NAT, 0, 1, Timedelta::NANOS_PER_DAY, i64::MAX] {
16911 assert_eq!(former_impl(value), Timedelta::isoformat(value));
16912 }
16913 for &value in values.iter().filter(|value| **value >= 0) {
16914 assert_eq!(former_impl(value), Timedelta::isoformat(value));
16915 }
16916
16917 for _ in 0..2 {
16918 black_box(elapsed(&values, former_impl));
16919 black_box(elapsed(&values, Timedelta::isoformat));
16920 }
16921
16922 let mut former = Vec::with_capacity(18);
16923 let mut candidate = Vec::with_capacity(18);
16924 for block in 0..9 {
16925 if block % 2 == 0 {
16926 former.push(elapsed(&values, former_impl));
16927 candidate.push(elapsed(&values, Timedelta::isoformat));
16928 candidate.push(elapsed(&values, Timedelta::isoformat));
16929 former.push(elapsed(&values, former_impl));
16930 } else {
16931 candidate.push(elapsed(&values, Timedelta::isoformat));
16932 former.push(elapsed(&values, former_impl));
16933 former.push(elapsed(&values, former_impl));
16934 candidate.push(elapsed(&values, Timedelta::isoformat));
16935 }
16936 }
16937
16938 let former_p50 = median(&mut former);
16939 let candidate_p50 = median(&mut candidate);
16940 eprintln!(
16941 "ISOFORMAT_AB rows={} former_p50_ns={} candidate_p50_ns={} ratio={:.6} former_ns_per_row={:.3} candidate_ns_per_row={:.3}",
16942 values.len(),
16943 former_p50,
16944 candidate_p50,
16945 former_p50 as f64 / candidate_p50 as f64,
16946 former_p50 as f64 / values.len() as f64,
16947 candidate_p50 as f64 / values.len() as f64,
16948 );
16949 eprintln!("ISOFORMAT_AB former_samples_ns={former:?}");
16950 eprintln!("ISOFORMAT_AB candidate_samples_ns={candidate:?}");
16951 }
16952
16953 #[test]
16954 fn timedelta_floor_ceil_round() {
16955 use super::Timedelta;
16956 let nanos = Timedelta::NANOS_PER_HOUR + 30 * Timedelta::NANOS_PER_MIN;
16957
16958 assert_eq!(Timedelta::floor(nanos, "h"), Timedelta::NANOS_PER_HOUR);
16960 assert_eq!(Timedelta::floor(nanos, "d"), 0);
16961
16962 assert_eq!(Timedelta::ceil(nanos, "h"), 2 * Timedelta::NANOS_PER_HOUR);
16964 assert_eq!(Timedelta::ceil(nanos, "d"), Timedelta::NANOS_PER_DAY);
16965
16966 assert_eq!(Timedelta::round(nanos, "h"), 2 * Timedelta::NANOS_PER_HOUR);
16968
16969 assert_eq!(Timedelta::floor(Timedelta::NAT, "h"), Timedelta::NAT);
16971 assert_eq!(Timedelta::ceil(Timedelta::NAT, "h"), Timedelta::NAT);
16972 assert_eq!(Timedelta::round(Timedelta::NAT, "h"), Timedelta::NAT);
16973
16974 assert_eq!(Timedelta::floor(nanos, "invalid"), Timedelta::NAT);
16976 }
16977
16978 #[test]
16979 fn timedelta_floor_ceil_negative_use_euclidean_rounding_t79yh() {
16980 use super::Timedelta;
16981
16982 assert_eq!(
16983 Timedelta::floor(-1, "s"),
16984 -Timedelta::NANOS_PER_SEC,
16985 "floor(-1ns, 1s)"
16986 );
16987 assert_eq!(Timedelta::ceil(-1, "s"), 0, "ceil(-1ns, 1s)");
16988 assert_eq!(
16989 Timedelta::floor(-1_500_000_000, "s"),
16990 -2 * Timedelta::NANOS_PER_SEC
16991 );
16992 assert_eq!(
16993 Timedelta::ceil(-1_500_000_000, "s"),
16994 -Timedelta::NANOS_PER_SEC
16995 );
16996 assert_eq!(
16997 Timedelta::floor(-Timedelta::NANOS_PER_SEC, "s"),
16998 -Timedelta::NANOS_PER_SEC
16999 );
17000 assert_eq!(
17001 Timedelta::ceil(-Timedelta::NANOS_PER_SEC, "s"),
17002 -Timedelta::NANOS_PER_SEC
17003 );
17004 assert_eq!(
17005 Timedelta::floor(1_500_000_000, "s"),
17006 Timedelta::NANOS_PER_SEC
17007 );
17008 assert_eq!(
17009 Timedelta::ceil(1_500_000_000, "s"),
17010 2 * Timedelta::NANOS_PER_SEC
17011 );
17012 }
17013
17014 #[test]
17015 fn timedelta_scalar_dtype() {
17016 let td = Scalar::Timedelta64(86_400_000_000_000);
17017 assert_eq!(td.dtype(), DType::Timedelta64);
17018 }
17019
17020 #[test]
17021 fn timedelta_scalar_is_missing() {
17022 use super::Timedelta;
17023 let valid = Scalar::Timedelta64(1000);
17024 let nat = Scalar::Timedelta64(Timedelta::NAT);
17025 assert!(!valid.is_missing());
17026 assert!(nat.is_missing());
17027 }
17028
17029 #[test]
17030 fn dtype_utf8_deserializes_legacy_aliases() {
17031 let dtype: DType = serde_json::from_str("\"str\"").unwrap();
17032 assert_eq!(dtype, DType::Utf8);
17033
17034 let dtype: DType = serde_json::from_str("\"string\"").unwrap();
17035 assert_eq!(dtype, DType::Utf8);
17036 }
17037
17038 #[test]
17039 fn datetime64_dtype_carries_timezone_00ze3() {
17040 let naive = DType::datetime64_naive();
17041 assert_eq!(naive.timezone(), None);
17042 assert_eq!(naive.display_name(), "datetime64[ns]");
17043
17044 let aware = DType::datetime64_tz("America/New_York");
17045 assert_eq!(aware.timezone(), Some("America/New_York"));
17046 assert_eq!(aware.display_name(), "datetime64[ns, America/New_York]");
17047 assert_ne!(aware, naive, "timezone must participate in dtype identity");
17048
17049 let json = serde_json::to_string(&aware).expect("serialize timezone dtype");
17050 assert_eq!(
17051 serde_json::from_str::<DType>(&json).expect("deserialize timezone dtype"),
17052 aware
17053 );
17054 }
17055
17056 #[test]
17057 fn scalar_utf8_deserializes_legacy_aliases() {
17058 let scalar: Scalar = serde_json::from_str(r#"{"kind":"str","value":"x"}"#).unwrap();
17059 assert_eq!(scalar, Scalar::Utf8("x".to_owned()));
17060
17061 let scalar: Scalar = serde_json::from_str(r#"{"kind":"string","value":"y"}"#).unwrap();
17062 assert_eq!(scalar, Scalar::Utf8("y".to_owned()));
17063 }
17064
17065 #[test]
17066 fn nancumsum_skips_nulls_and_accumulates() {
17067 let values = vec![
17068 Scalar::Float64(1.0),
17069 Scalar::Null(NullKind::NaN),
17070 Scalar::Float64(2.0),
17071 Scalar::Float64(3.0),
17072 ];
17073 let out = super::nancumsum(&values);
17074 assert!(matches!(out[0], Scalar::Float64(v) if (v - 1.0).abs() < 1e-9));
17075 assert!(out[1].is_missing());
17076 assert!(matches!(out[2], Scalar::Float64(v) if (v - 3.0).abs() < 1e-9));
17077 assert!(matches!(out[3], Scalar::Float64(v) if (v - 6.0).abs() < 1e-9));
17078 }
17079
17080 #[test]
17081 fn nancumprod_skips_nulls_and_multiplies() {
17082 let values = vec![
17083 Scalar::Float64(2.0),
17084 Scalar::Null(NullKind::NaN),
17085 Scalar::Float64(3.0),
17086 Scalar::Float64(4.0),
17087 ];
17088 let out = super::nancumprod(&values);
17089 assert!(matches!(out[0], Scalar::Float64(v) if (v - 2.0).abs() < 1e-9));
17090 assert!(out[1].is_missing());
17091 assert!(matches!(out[2], Scalar::Float64(v) if (v - 6.0).abs() < 1e-9));
17092 assert!(matches!(out[3], Scalar::Float64(v) if (v - 24.0).abs() < 1e-9));
17093 }
17094
17095 #[test]
17096 fn nancummax_tracks_running_max() {
17097 let values = vec![
17098 Scalar::Float64(1.0),
17099 Scalar::Float64(3.0),
17100 Scalar::Null(NullKind::NaN),
17101 Scalar::Float64(2.0),
17102 Scalar::Float64(5.0),
17103 ];
17104 let out = super::nancummax(&values);
17105 assert_eq!(out[0], Scalar::Float64(1.0));
17106 assert_eq!(out[1], Scalar::Float64(3.0));
17107 assert!(out[2].is_missing());
17108 assert_eq!(out[3], Scalar::Float64(3.0));
17109 assert_eq!(out[4], Scalar::Float64(5.0));
17110 }
17111
17112 #[test]
17113 fn nancummin_tracks_running_min() {
17114 let values = vec![
17115 Scalar::Float64(5.0),
17116 Scalar::Float64(3.0),
17117 Scalar::Null(NullKind::NaN),
17118 Scalar::Float64(4.0),
17119 Scalar::Float64(1.0),
17120 ];
17121 let out = super::nancummin(&values);
17122 assert_eq!(out[0], Scalar::Float64(5.0));
17123 assert_eq!(out[1], Scalar::Float64(3.0));
17124 assert!(out[2].is_missing());
17125 assert_eq!(out[3], Scalar::Float64(3.0));
17126 assert_eq!(out[4], Scalar::Float64(1.0));
17127 }
17128
17129 #[test]
17130 fn nancumsum_timedelta64_preserves_dtype_x0x91() {
17131 let one_hour = 3_600 * 1_000_000_000_i64;
17134 let values = vec![
17135 Scalar::Timedelta64(one_hour),
17136 Scalar::Timedelta64(2 * one_hour),
17137 Scalar::Timedelta64(3 * one_hour),
17138 ];
17139 let out = super::nancumsum(&values);
17140 assert_eq!(out[0], Scalar::Timedelta64(one_hour));
17141 assert_eq!(out[1], Scalar::Timedelta64(3 * one_hour));
17142 assert_eq!(out[2], Scalar::Timedelta64(6 * one_hour));
17143 }
17144
17145 #[test]
17146 fn nancummax_nancummin_timedelta64_preserves_dtype_x0x91() {
17147 let one_hour = 3_600 * 1_000_000_000_i64;
17148 let values = vec![
17149 Scalar::Timedelta64(2 * one_hour),
17150 Scalar::Timedelta64(5 * one_hour),
17151 Scalar::Timedelta64(one_hour),
17152 Scalar::Timedelta64(3 * one_hour),
17153 ];
17154 let mx = super::nancummax(&values);
17155 assert_eq!(mx[0], Scalar::Timedelta64(2 * one_hour));
17156 assert_eq!(mx[1], Scalar::Timedelta64(5 * one_hour));
17157 assert_eq!(mx[2], Scalar::Timedelta64(5 * one_hour));
17158 assert_eq!(mx[3], Scalar::Timedelta64(5 * one_hour));
17159
17160 let mn = super::nancummin(&values);
17161 assert_eq!(mn[0], Scalar::Timedelta64(2 * one_hour));
17162 assert_eq!(mn[1], Scalar::Timedelta64(2 * one_hour));
17163 assert_eq!(mn[2], Scalar::Timedelta64(one_hour));
17164 assert_eq!(mn[3], Scalar::Timedelta64(one_hour));
17165 }
17166
17167 #[test]
17168 fn nancumulative_timedelta64_skips_nat_x0x91() {
17169 let one_hour = 3_600 * 1_000_000_000_i64;
17170 let values = vec![
17171 Scalar::Timedelta64(one_hour),
17172 Scalar::Timedelta64(Timedelta::NAT),
17173 Scalar::Timedelta64(2 * one_hour),
17174 ];
17175 let cs = super::nancumsum(&values);
17176 assert_eq!(cs[0], Scalar::Timedelta64(one_hour));
17177 assert!(cs[1].is_missing());
17178 assert_eq!(cs[2], Scalar::Timedelta64(3 * one_hour));
17179 }
17180
17181 #[test]
17182 fn nancumulative_matches_numeric_and_timedelta_oracle_k63oz() {
17183 fn next(seed: &mut u64) -> u64 {
17186 *seed = seed
17187 .wrapping_mul(3202034522624059733)
17188 .wrapping_add(4354685564936845319);
17189 *seed
17190 }
17191
17192 fn assert_vec(case: usize, family: &str, op: &str, actual: &[Scalar], expected: &[Scalar]) {
17193 assert_eq!(
17194 actual.len(),
17195 expected.len(),
17196 "case={case} family={family} op={op}: length mismatch"
17197 );
17198 for (pos, (actual, expected)) in actual.iter().zip(expected.iter()).enumerate() {
17199 assert!(
17200 actual.semantic_eq(expected),
17201 "case={case} family={family} op={op} pos={pos}: expected {expected:?}, got {actual:?}"
17202 );
17203 }
17204 }
17205
17206 fn expected_numeric(
17207 values: &[Scalar],
17208 ) -> (Vec<Scalar>, Vec<Scalar>, Vec<Scalar>, Vec<Scalar>) {
17209 let mut sum = Vec::with_capacity(values.len());
17210 let mut prod = Vec::with_capacity(values.len());
17211 let mut max = Vec::with_capacity(values.len());
17212 let mut min = Vec::with_capacity(values.len());
17213 let mut running_sum = 0.0_f64;
17214 let mut running_prod = 1.0_f64;
17215 let mut running_max: Option<f64> = None;
17216 let mut running_min: Option<f64> = None;
17217
17218 for value in values {
17219 if value.is_missing() {
17220 sum.push(Scalar::Null(NullKind::NaN));
17221 prod.push(Scalar::Null(NullKind::NaN));
17222 max.push(Scalar::Null(NullKind::NaN));
17223 min.push(Scalar::Null(NullKind::NaN));
17224 continue;
17225 }
17226 let Ok(value) = value.to_f64() else {
17227 sum.push(Scalar::Null(NullKind::NaN));
17228 prod.push(Scalar::Null(NullKind::NaN));
17229 max.push(Scalar::Null(NullKind::NaN));
17230 min.push(Scalar::Null(NullKind::NaN));
17231 continue;
17232 };
17233 if value.is_nan() {
17234 sum.push(Scalar::Null(NullKind::NaN));
17235 prod.push(Scalar::Null(NullKind::NaN));
17236 max.push(Scalar::Null(NullKind::NaN));
17237 min.push(Scalar::Null(NullKind::NaN));
17238 continue;
17239 }
17240 running_sum += value;
17241 running_prod *= value;
17242 running_max = Some(running_max.map_or(value, |current| current.max(value)));
17243 running_min = Some(running_min.map_or(value, |current| current.min(value)));
17244 sum.push(Scalar::Float64(running_sum));
17245 prod.push(Scalar::Float64(running_prod));
17246 max.push(Scalar::Float64(running_max.expect("initialized")));
17247 min.push(Scalar::Float64(running_min.expect("initialized")));
17248 }
17249
17250 (sum, prod, max, min)
17251 }
17252
17253 fn expected_timedelta(values: &[Scalar]) -> (Vec<Scalar>, Vec<Scalar>, Vec<Scalar>) {
17254 let mut sum = Vec::with_capacity(values.len());
17255 let mut max = Vec::with_capacity(values.len());
17256 let mut min = Vec::with_capacity(values.len());
17257 let mut running_sum = 0_i128;
17258 let mut running_max: Option<i64> = None;
17259 let mut running_min: Option<i64> = None;
17260
17261 for value in values {
17262 if value.is_missing() {
17263 sum.push(Scalar::Null(NullKind::NaT));
17264 max.push(Scalar::Null(NullKind::NaT));
17265 min.push(Scalar::Null(NullKind::NaT));
17266 continue;
17267 }
17268 let Scalar::Timedelta64(ns) = value else {
17269 sum.push(Scalar::Null(NullKind::NaT));
17270 max.push(Scalar::Null(NullKind::NaT));
17271 min.push(Scalar::Null(NullKind::NaT));
17272 continue;
17273 };
17274 running_sum = running_sum.saturating_add(i128::from(*ns));
17275 running_max = Some(running_max.map_or(*ns, |current| current.max(*ns)));
17276 running_min = Some(running_min.map_or(*ns, |current| current.min(*ns)));
17277 sum.push(super::timedelta_ns_to_scalar(running_sum));
17280 max.push(Scalar::Timedelta64(running_max.expect("initialized")));
17281 min.push(Scalar::Timedelta64(running_min.expect("initialized")));
17282 }
17283
17284 (sum, max, min)
17285 }
17286
17287 let mut seed = 0xc0de_c63a_5eed_0421_u64;
17288 for case in 0..260 {
17289 let len = (next(&mut seed) % 89 + 1) as usize;
17290
17291 let mut numeric = Vec::with_capacity(len);
17292 numeric.push(Scalar::Int64(case as i64 - 130));
17293 for _ in 1..len {
17294 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
17295 numeric.push(match next(&mut seed) % 8 {
17296 0 => Scalar::Null(NullKind::Null),
17297 1 => Scalar::Null(NullKind::NaN),
17298 2 => Scalar::Float64(f64::NAN),
17299 3 => Scalar::Bool(raw & 1 == 0),
17300 4 => Scalar::Int64(raw % 251),
17301 5 => Scalar::Float64(raw as f64 / 79.0),
17302 6 => Scalar::Float64(0.0),
17303 _ => Scalar::Float64(-0.0),
17304 });
17305 }
17306 let (sum, prod, max, min) = expected_numeric(&numeric);
17307 assert_vec(case, "numeric", "cumsum", &super::nancumsum(&numeric), &sum);
17308 assert_vec(
17309 case,
17310 "numeric",
17311 "cumprod",
17312 &super::nancumprod(&numeric),
17313 &prod,
17314 );
17315 assert_vec(case, "numeric", "cummax", &super::nancummax(&numeric), &max);
17316 assert_vec(case, "numeric", "cummin", &super::nancummin(&numeric), &min);
17317
17318 let mut timedeltas = Vec::with_capacity(len);
17319 timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
17320 for _ in 1..len {
17321 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
17322 timedeltas.push(match next(&mut seed) % 7 {
17323 0 => Scalar::Null(NullKind::Null),
17324 1 => Scalar::Timedelta64(i64::MIN),
17325 _ => Scalar::Timedelta64(raw),
17326 });
17327 }
17328 let (td_sum, td_max, td_min) = expected_timedelta(&timedeltas);
17329 assert_vec(
17330 case,
17331 "timedelta",
17332 "cumsum",
17333 &super::nancumsum(&timedeltas),
17334 &td_sum,
17335 );
17336 assert_vec(
17337 case,
17338 "timedelta",
17339 "cummax",
17340 &super::nancummax(&timedeltas),
17341 &td_max,
17342 );
17343 assert_vec(
17344 case,
17345 "timedelta",
17346 "cummin",
17347 &super::nancummin(&timedeltas),
17348 &td_min,
17349 );
17350 }
17351 }
17352
17353 #[test]
17354 fn nanquantile_linear_interpolation_matches_numpy() {
17355 let values = vec![
17356 Scalar::Float64(1.0),
17357 Scalar::Float64(2.0),
17358 Scalar::Float64(3.0),
17359 Scalar::Float64(4.0),
17360 Scalar::Float64(5.0),
17361 ];
17362 let q = super::nanquantile(&values, 0.5);
17364 assert!(matches!(q, Scalar::Float64(v) if (v - 3.0).abs() < 1e-9));
17365 let q25 = super::nanquantile(&values, 0.25);
17367 assert!(matches!(q25, Scalar::Float64(v) if (v - 2.0).abs() < 1e-9));
17368 }
17369
17370 #[test]
17371 fn nanquantile_ignores_nulls() {
17372 let values = vec![
17373 Scalar::Float64(1.0),
17374 Scalar::Null(NullKind::NaN),
17375 Scalar::Float64(3.0),
17376 ];
17377 let q = super::nanquantile(&values, 0.5);
17378 assert!(matches!(q, Scalar::Float64(v) if (v - 2.0).abs() < 1e-9));
17379 }
17380
17381 #[test]
17382 fn nanquantile_empty_and_out_of_range_yield_null() {
17383 assert!(super::nanquantile(&[], 0.5).is_missing());
17384 assert!(super::nanquantile(&[Scalar::Float64(1.0)], 1.5).is_missing());
17385 assert!(super::nanquantile(&[Scalar::Float64(1.0)], -0.1).is_missing());
17386 }
17387
17388 #[test]
17389 fn nanquantile_timedelta64_preserves_dtype_5djk7() {
17390 let one_hour: i64 = 3_600 * 1_000_000_000;
17393 let vals = vec![
17394 Scalar::Timedelta64(one_hour),
17395 Scalar::Timedelta64(2 * one_hour),
17396 Scalar::Timedelta64(3 * one_hour),
17397 Scalar::Timedelta64(4 * one_hour),
17398 Scalar::Timedelta64(5 * one_hour),
17399 ];
17400 assert_eq!(
17401 super::nanquantile(&vals, 0.5),
17402 Scalar::Timedelta64(3 * one_hour)
17403 );
17404 assert_eq!(
17405 super::nanquantile(&vals, 0.0),
17406 Scalar::Timedelta64(one_hour)
17407 );
17408 assert_eq!(
17409 super::nanquantile(&vals, 1.0),
17410 Scalar::Timedelta64(5 * one_hour)
17411 );
17412 }
17413
17414 #[test]
17415 fn nanquantile_timedelta64_linear_interpolation_5djk7() {
17416 let one_hour: i64 = 3_600 * 1_000_000_000;
17417 let vals = vec![
17418 Scalar::Timedelta64(one_hour),
17419 Scalar::Timedelta64(3 * one_hour),
17420 ];
17421 assert_eq!(
17423 super::nanquantile(&vals, 0.5),
17424 Scalar::Timedelta64(2 * one_hour)
17425 );
17426 }
17427
17428 #[test]
17429 fn nanquantile_matches_numeric_and_timedelta_oracle_ecb7r() {
17430 fn next(seed: &mut u64) -> u64 {
17433 *seed = seed
17434 .wrapping_mul(3202034522624059733)
17435 .wrapping_add(4354685564936845319);
17436 *seed
17437 }
17438
17439 fn interpolated(sorted: &[f64], q: f64) -> f64 {
17440 if sorted.len() == 1 {
17441 return sorted[0];
17442 }
17443 let pos = q * (sorted.len() - 1) as f64;
17444 let lo = pos.floor() as usize;
17445 let hi = pos.ceil() as usize;
17446 if lo == hi {
17447 sorted[lo]
17448 } else {
17449 let weight = pos - lo as f64;
17450 sorted[lo] + (sorted[hi] - sorted[lo]) * weight
17451 }
17452 }
17453
17454 fn expected_numeric(values: &[Scalar], q: f64) -> Scalar {
17455 if !(0.0..=1.0).contains(&q) {
17456 return Scalar::Null(NullKind::NaN);
17457 }
17458 let mut samples = values
17459 .iter()
17460 .filter(|value| !value.is_missing())
17461 .filter_map(|value| value.to_f64().ok())
17462 .collect::<Vec<_>>();
17463 if samples.is_empty() {
17464 return Scalar::Null(NullKind::NaN);
17465 }
17466 samples.sort_by(|left, right| left.partial_cmp(right).expect("finite values"));
17467 Scalar::Float64(interpolated(&samples, q))
17468 }
17469
17470 fn expected_timedelta(values: &[Scalar], q: f64) -> Scalar {
17471 if !(0.0..=1.0).contains(&q) {
17472 return Scalar::Null(NullKind::NaN);
17473 }
17474 let mut samples = values
17475 .iter()
17476 .filter_map(|value| match value {
17477 Scalar::Timedelta64(ns) if !value.is_missing() => Some(*ns as f64),
17478 _ => None,
17479 })
17480 .collect::<Vec<_>>();
17481 if samples.is_empty() {
17482 return Scalar::Timedelta64(Timedelta::NAT);
17485 }
17486 samples.sort_by(|left, right| left.partial_cmp(right).expect("finite values"));
17487 Scalar::Timedelta64(interpolated(&samples, q) as i64)
17488 }
17489
17490 fn assert_quantile(case: usize, family: &str, values: &[Scalar], q: f64, expected: Scalar) {
17491 let actual = super::nanquantile(values, q);
17492 assert!(
17493 actual.semantic_eq(&expected),
17494 "case={case} family={family} q={q}: expected {expected:?}, got {actual:?} for {values:?}"
17495 );
17496 }
17497
17498 let numeric_all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
17499 assert_quantile(
17500 usize::MAX,
17501 "numeric_all_missing",
17502 &numeric_all_missing,
17503 0.5,
17504 expected_numeric(&numeric_all_missing, 0.5),
17505 );
17506 assert_quantile(
17507 usize::MAX - 1,
17508 "numeric_out_of_range",
17509 &[Scalar::Float64(1.0), Scalar::Float64(2.0)],
17510 1.25,
17511 Scalar::Null(NullKind::NaN),
17512 );
17513
17514 let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
17515 assert_quantile(
17516 usize::MAX - 2,
17517 "timedelta_all_missing",
17518 &td_all_missing,
17519 0.5,
17520 expected_timedelta(&td_all_missing, 0.5),
17521 );
17522 assert_quantile(
17523 usize::MAX - 3,
17524 "timedelta_out_of_range",
17525 &[Scalar::Timedelta64(1), Scalar::Timedelta64(2)],
17526 -0.25,
17527 Scalar::Null(NullKind::NaN),
17528 );
17529
17530 let mut seed = 0x4a17_1e5e_0b5e_a11d_u64;
17531 for case in 0..260 {
17532 let len = (next(&mut seed) % 83 + 1) as usize;
17533 let q = match next(&mut seed) % 8 {
17534 0 => 0.0,
17535 1 => 0.25,
17536 2 => 0.5,
17537 3 => 0.75,
17538 4 => 1.0,
17539 _ => (next(&mut seed) % 1_001) as f64 / 1_000.0,
17540 };
17541
17542 let mut numeric = Vec::with_capacity(len);
17543 numeric.push(Scalar::Int64(case as i64 - 130));
17544 for _ in 1..len {
17545 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
17546 numeric.push(match next(&mut seed) % 8 {
17547 0 => Scalar::Null(NullKind::Null),
17548 1 => Scalar::Null(NullKind::NaN),
17549 2 => Scalar::Float64(f64::NAN),
17550 3 => Scalar::Bool(raw & 1 == 0),
17551 4 => Scalar::Int64(raw % 251),
17552 5 => Scalar::Float64(raw as f64 / 67.0),
17553 6 => Scalar::Float64(0.0),
17554 _ => Scalar::Float64(-0.0),
17555 });
17556 }
17557 assert_quantile(case, "numeric", &numeric, q, expected_numeric(&numeric, q));
17558
17559 let mut timedeltas = Vec::with_capacity(len);
17560 timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
17561 for _ in 1..len {
17562 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
17563 timedeltas.push(match next(&mut seed) % 7 {
17564 0 => Scalar::Null(NullKind::Null),
17565 1 => Scalar::Timedelta64(i64::MIN),
17566 _ => Scalar::Timedelta64(raw),
17567 });
17568 }
17569 assert_quantile(
17570 case,
17571 "timedelta",
17572 &timedeltas,
17573 q,
17574 expected_timedelta(&timedeltas, q),
17575 );
17576 }
17577 }
17578
17579 #[test]
17580 fn nanargmax_returns_first_position() {
17581 let values = vec![
17582 Scalar::Float64(1.0),
17583 Scalar::Null(NullKind::NaN),
17584 Scalar::Float64(4.0),
17585 Scalar::Float64(4.0),
17586 Scalar::Float64(2.0),
17587 ];
17588 assert_eq!(super::nanargmax(&values), Some(2));
17589 }
17590
17591 #[test]
17592 fn nanargmin_returns_first_position() {
17593 let values = vec![
17594 Scalar::Float64(3.0),
17595 Scalar::Null(NullKind::NaN),
17596 Scalar::Float64(1.0),
17597 Scalar::Float64(1.0),
17598 ];
17599 assert_eq!(super::nanargmin(&values), Some(2));
17600 }
17601
17602 #[test]
17603 fn nanargmax_all_missing_returns_none() {
17604 let values = vec![Scalar::Null(NullKind::NaN), Scalar::Null(NullKind::Null)];
17605 assert_eq!(super::nanargmax(&values), None);
17606 assert_eq!(super::nanargmin(&values), None);
17607 }
17608
17609 #[test]
17610 fn nanargmax_nanargmin_match_numeric_and_timedelta_oracle_unkj6() {
17611 fn next(seed: &mut u64) -> u64 {
17614 *seed = seed
17615 .wrapping_mul(2862933555777941757)
17616 .wrapping_add(3037000493);
17617 *seed
17618 }
17619
17620 fn expected_numeric(values: &[Scalar], find_max: bool) -> Option<usize> {
17621 let mut best: Option<(usize, f64)> = None;
17622 for (idx, value) in values.iter().enumerate() {
17623 if value.is_missing() {
17624 continue;
17625 }
17626 let Ok(value) = value.to_f64() else {
17627 continue;
17628 };
17629 if value.is_nan() {
17630 continue;
17631 }
17632 match best {
17633 None => best = Some((idx, value)),
17634 Some((_, current))
17635 if (find_max && value > current) || (!find_max && value < current) =>
17636 {
17637 best = Some((idx, value));
17638 }
17639 _ => {}
17640 }
17641 }
17642 best.map(|(idx, _)| idx)
17643 }
17644
17645 fn expected_timedelta(values: &[Scalar], find_max: bool) -> Option<usize> {
17646 let mut best: Option<(usize, i64)> = None;
17647 for (idx, value) in values.iter().enumerate() {
17648 if value.is_missing() {
17649 continue;
17650 }
17651 let Scalar::Timedelta64(ns) = value else {
17652 continue;
17653 };
17654 match best {
17655 None => best = Some((idx, *ns)),
17656 Some((_, current))
17657 if (find_max && *ns > current) || (!find_max && *ns < current) =>
17658 {
17659 best = Some((idx, *ns));
17660 }
17661 _ => {}
17662 }
17663 }
17664 best.map(|(idx, _)| idx)
17665 }
17666
17667 fn assert_args(
17668 case: usize,
17669 family: &str,
17670 values: &[Scalar],
17671 expected_min: Option<usize>,
17672 expected_max: Option<usize>,
17673 ) {
17674 assert_eq!(
17675 super::nanargmin(values),
17676 expected_min,
17677 "case={case} family={family}: nanargmin mismatch for {values:?}"
17678 );
17679 assert_eq!(
17680 super::nanargmax(values),
17681 expected_max,
17682 "case={case} family={family}: nanargmax mismatch for {values:?}"
17683 );
17684 }
17685
17686 let all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
17687 assert_args(usize::MAX, "numeric_all_missing", &all_missing, None, None);
17688 let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
17689 assert_args(
17690 usize::MAX - 1,
17691 "timedelta_all_missing",
17692 &td_all_missing,
17693 None,
17694 None,
17695 );
17696 let positive_int64_endpoint = [
17697 Scalar::Int64(i64::MAX - 1),
17698 Scalar::Null(NullKind::Null),
17699 Scalar::Int64(i64::MAX),
17700 ];
17701 assert_args(
17702 usize::MAX - 2,
17703 "int64_positive_endpoint_exact_order",
17704 &positive_int64_endpoint,
17705 Some(0),
17706 Some(2),
17707 );
17708 let negative_int64_endpoint = [
17709 Scalar::Int64(i64::MIN + 2),
17710 Scalar::Null(NullKind::NaN),
17711 Scalar::Int64(i64::MIN + 1),
17712 ];
17713 assert_args(
17714 usize::MAX - 3,
17715 "int64_negative_endpoint_exact_order",
17716 &negative_int64_endpoint,
17717 Some(2),
17718 Some(0),
17719 );
17720
17721 let mut seed = 0xa126_5eed_ed9e_u64;
17722 for case in 0..260 {
17723 let len = (next(&mut seed) % 83 + 1) as usize;
17724
17725 let mut numeric = Vec::with_capacity(len);
17726 numeric.push(Scalar::Int64(case as i64 - 130));
17727 if len > 1 {
17728 numeric.push(Scalar::Int64(case as i64 - 130));
17729 }
17730 for _ in numeric.len()..len {
17731 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
17732 numeric.push(match next(&mut seed) % 9 {
17733 0 => Scalar::Null(NullKind::Null),
17734 1 => Scalar::Null(NullKind::NaN),
17735 2 => Scalar::Float64(f64::NAN),
17736 3 => Scalar::Bool(raw & 1 == 0),
17737 4 => Scalar::Int64(raw % 211),
17738 5 => Scalar::Float64(raw as f64 / 47.0),
17739 6 => Scalar::Float64(0.0),
17740 7 => Scalar::Float64(-0.0),
17741 _ => Scalar::Float64(raw.signum() as f64 * f64::INFINITY),
17742 });
17743 }
17744 assert_args(
17745 case,
17746 "numeric",
17747 &numeric,
17748 expected_numeric(&numeric, false),
17749 expected_numeric(&numeric, true),
17750 );
17751
17752 let mut timedeltas = Vec::with_capacity(len);
17753 timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
17754 if len > 1 {
17755 timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
17756 }
17757 for _ in timedeltas.len()..len {
17758 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
17759 timedeltas.push(match next(&mut seed) % 7 {
17760 0 => Scalar::Null(NullKind::Null),
17761 1 => Scalar::Timedelta64(i64::MIN),
17762 _ => Scalar::Timedelta64(raw),
17763 });
17764 }
17765 assert_args(
17766 case,
17767 "timedelta",
17768 &timedeltas,
17769 expected_timedelta(&timedeltas, false),
17770 expected_timedelta(&timedeltas, true),
17771 );
17772 }
17773 }
17774
17775 #[test]
17776 fn nansem_matches_std_over_sqrt_n() {
17777 let values = vec![
17778 Scalar::Float64(2.0),
17779 Scalar::Float64(4.0),
17780 Scalar::Float64(4.0),
17781 Scalar::Float64(4.0),
17782 Scalar::Float64(5.0),
17783 Scalar::Float64(5.0),
17784 Scalar::Float64(7.0),
17785 Scalar::Float64(9.0),
17786 ];
17787 let sem = super::nansem(&values, 1);
17789 assert!(matches!(sem, Scalar::Float64(_)));
17790 let Scalar::Float64(v) = sem else {
17791 return;
17792 };
17793 assert!((v - 0.7559289460184544).abs() < 1e-9);
17794 }
17795
17796 #[test]
17797 fn nansem_grouped_is_sqrt_var_over_n_7hxqv() {
17798 let values = [
17801 Scalar::Float64(1.0),
17802 Scalar::Null(NullKind::NaN),
17803 Scalar::Float64(4.0),
17804 ];
17805 assert_eq!(super::nansem_grouped(&values, 1), Scalar::Float64(1.5));
17806 assert_eq!(
17808 super::nansem(&values, 1),
17809 Scalar::Float64(1.499_999_999_999_999_8)
17810 );
17811 assert!(super::nansem_grouped(&values[..1], 1).is_missing());
17812 }
17813
17814 #[test]
17815 fn grouped_reducers_add_as_pandas_group_kernels_xhogl() {
17816 let tenths: Vec<Scalar> = (0..10).map(|_| Scalar::Float64(0.1)).collect();
17820 assert_eq!(super::nansum_grouped(&tenths), Scalar::Float64(1.0));
17821 assert_eq!(super::nanmean_grouped(&tenths), Scalar::Float64(0.1));
17822 assert_eq!(super::nanvar_grouped(&tenths, 1), Scalar::Float64(0.0));
17823 assert_eq!(super::nanstd_grouped(&tenths, 1), Scalar::Float64(0.0));
17824 assert_eq!(
17826 super::nansum(&tenths),
17827 Scalar::Float64(0.999_999_999_999_999_9)
17828 );
17829 let mut sum = super::KahanSum::default();
17831 for value in [1.0, f64::INFINITY, 2.0] {
17832 sum.add(value);
17833 }
17834 assert_eq!(sum.sum(), f64::INFINITY);
17835 let gapped = [
17837 Scalar::Float64(1.0),
17838 Scalar::Null(NullKind::NaN),
17839 Scalar::Float64(4.0),
17840 ];
17841 assert_eq!(super::nanmean_grouped(&gapped), Scalar::Float64(2.5));
17842 assert_eq!(super::nanvar_grouped(&gapped, 1), Scalar::Float64(4.5));
17843 assert!(super::nanvar_grouped(&gapped[..1], 1).is_missing());
17844 let spans = [Scalar::Timedelta64(1), Scalar::Timedelta64(2)];
17846 assert_eq!(super::nansum_grouped(&spans), super::nansum(&spans));
17847 }
17848
17849 #[test]
17850 fn grouped_skew_is_pandas_online_group_skew_vjfq9() {
17851 let group = [
17854 Scalar::Float64(1.0),
17855 Scalar::Null(NullKind::NaN),
17856 Scalar::Float64(4.0),
17857 Scalar::Float64(8.0),
17858 ];
17859 assert_eq!(
17860 super::nanskew_grouped(&group),
17861 Scalar::Float64(0.423_273_160_268_006_15)
17862 );
17863 let long: Vec<Scalar> = (0..2922_i32)
17866 .map(|i| Scalar::Float64(f64::from((i * 7919) % 1000) / 7.0))
17867 .collect();
17868 let glibc_pow = Scalar::Float64(-0.002_284_383_734_800_801_4);
17869 if cfg!(all(target_os = "linux", target_env = "gnu")) {
17875 assert_eq!(super::nanskew_grouped(&long), glibc_pow);
17876 } else {
17877 let sqrt = Scalar::Float64(-0.002_284_383_734_800_802);
17878 assert!([glibc_pow, sqrt].contains(&super::nanskew_grouped(&long)));
17879 }
17880 let constant = [7.0; 3].map(Scalar::Float64);
17883 assert_eq!(super::nanskew_grouped(&constant), Scalar::Float64(0.0));
17884 assert!(super::nanskew_grouped(&group[..2]).is_missing());
17885 let with_inf = [1.0, f64::INFINITY, 2.0, 5.0].map(Scalar::Float64);
17886 assert!(super::nanskew_grouped(&with_inf).is_missing());
17887 }
17888
17889 #[test]
17890 fn nansem_single_buffer_matches_former_numeric_bits_jgwg4() {
17891 fn former(values: &[Scalar], ddof: usize) -> Scalar {
17892 let nums = super::collect_finite(values);
17893 if nums.len() <= ddof {
17894 return Scalar::Null(NullKind::NaN);
17895 }
17896 match super::nanstd(values, ddof) {
17897 Scalar::Float64(std) => Scalar::Float64(std / (nums.len() as f64).sqrt()),
17898 other => other,
17899 }
17900 }
17901
17902 fn assert_same_bits(values: &[Scalar], ddof: usize) {
17903 let expected = former(values, ddof);
17904 let actual = super::nansem(values, ddof);
17905 match (&expected, &actual) {
17906 (Scalar::Float64(expected), Scalar::Float64(actual)) => {
17907 assert_eq!(
17908 actual.to_bits(),
17909 expected.to_bits(),
17910 "values={values:?} ddof={ddof}"
17911 );
17912 }
17913 _ => assert!(
17914 actual.semantic_eq(&expected),
17915 "values={values:?} ddof={ddof}: expected {expected:?}, got {actual:?}"
17916 ),
17917 }
17918 }
17919
17920 let mut generated = Vec::with_capacity(4_096);
17921 for idx in 0..4_096_i64 {
17922 generated.push(match idx % 257 {
17923 0 => Scalar::Null(NullKind::NaN),
17924 1 => Scalar::Float64(-0.0),
17925 2 => Scalar::Float64(0.0),
17926 _ if idx % 2 == 0 => Scalar::Int64(idx - 2_048),
17927 _ => Scalar::Float64((idx - 2_048) as f64 / 17.0),
17928 });
17929 }
17930
17931 let cases = [
17932 Vec::new(),
17933 vec![Scalar::Int64(1)],
17934 vec![
17935 Scalar::Null(NullKind::Null),
17936 Scalar::Float64(f64::NAN),
17937 Scalar::Int64(i64::MIN),
17938 Scalar::Int64(i64::MAX),
17939 Scalar::Float64(-0.0),
17940 Scalar::Float64(0.0),
17941 ],
17942 generated,
17943 ];
17944 for values in &cases {
17945 for ddof in [0, 1, values.len(), values.len().saturating_add(1)] {
17946 assert_same_bits(values, ddof);
17947 }
17948 }
17949 }
17950
17951 #[test]
17952 #[ignore = "foreground release A/B harness"]
17953 fn nansem_single_buffer_allocator_preconditioned_ab_jgwg4() {
17954 const ROWS: usize = 262_144;
17955 const BATCH: usize = 8;
17956 const BLOCKS: usize = 9;
17957 const PRECONDITION_CALLS: usize = 2;
17958
17959 fn former(values: &[Scalar], ddof: usize) -> Scalar {
17960 let nums = super::collect_finite(values);
17961 if nums.len() <= ddof {
17962 return Scalar::Null(NullKind::NaN);
17963 }
17964 match super::nanstd(values, ddof) {
17965 Scalar::Float64(std) => Scalar::Float64(std / (nums.len() as f64).sqrt()),
17966 other => other,
17967 }
17968 }
17969
17970 fn evaluate(values: &[Scalar], candidate: bool) -> Scalar {
17971 let values = std::hint::black_box(values);
17972 if candidate {
17973 super::nansem(values, 1)
17974 } else {
17975 former(values, 1)
17976 }
17977 }
17978
17979 fn elapsed_ns(values: &[Scalar], candidate: bool) -> u128 {
17980 for _ in 0..PRECONDITION_CALLS {
17981 std::hint::black_box(evaluate(values, candidate));
17982 }
17983 let started = std::time::Instant::now();
17984 for _ in 0..BATCH {
17985 std::hint::black_box(evaluate(values, candidate));
17986 }
17987 started.elapsed().as_nanos()
17988 }
17989
17990 fn median(mut samples: Vec<u128>) -> u128 {
17991 samples.sort_unstable();
17992 samples[samples.len() / 2]
17993 }
17994
17995 fn spread(a: u128, b: u128) -> f64 {
17996 a.abs_diff(b) as f64 / ((a + b) as f64 / 2.0)
17997 }
17998
17999 let values = (0..ROWS)
18000 .map(|idx| {
18001 if idx % 257 == 0 {
18002 Scalar::Null(NullKind::NaN)
18003 } else {
18004 Scalar::Int64((idx % 8_191) as i64 - 4_095)
18005 }
18006 })
18007 .collect::<Vec<_>>();
18008
18009 let expected_bits = match former(&values, 1) {
18010 Scalar::Float64(value) => Some(value.to_bits()),
18011 _ => None,
18012 };
18013 let actual_bits = match super::nansem(&values, 1) {
18014 Scalar::Float64(value) => Some(value.to_bits()),
18015 _ => None,
18016 };
18017 assert!(
18018 expected_bits.is_some(),
18019 "numeric nansem must return Float64"
18020 );
18021 assert_eq!(actual_bits, expected_bits, "A/B output bits");
18022
18023 std::hint::black_box(evaluate(&values, false));
18024 std::hint::black_box(evaluate(&values, true));
18025
18026 let body_started = std::time::Instant::now();
18027 let mut former_a = Vec::with_capacity(BLOCKS);
18028 let mut former_b = Vec::with_capacity(BLOCKS);
18029 let mut candidate_a = Vec::with_capacity(BLOCKS);
18030 let mut candidate_b = Vec::with_capacity(BLOCKS);
18031 for block in 0..BLOCKS {
18032 let order = if block % 2 == 0 {
18033 [(false, 0), (true, 0), (true, 1), (false, 1)]
18034 } else {
18035 [(true, 1), (false, 1), (false, 0), (true, 0)]
18036 };
18037 for (candidate, duplicate) in order {
18038 let elapsed = elapsed_ns(&values, candidate);
18039 match (candidate, duplicate) {
18040 (false, 0) => former_a.push(elapsed),
18041 (false, _) => former_b.push(elapsed),
18042 (true, 0) => candidate_a.push(elapsed),
18043 (true, _) => candidate_b.push(elapsed),
18044 }
18045 }
18046 }
18047
18048 let former_a = median(former_a) / BATCH as u128;
18049 let former_b = median(former_b) / BATCH as u128;
18050 let candidate_a = median(candidate_a) / BATCH as u128;
18051 let candidate_b = median(candidate_b) / BATCH as u128;
18052 let former_mean = (former_a + former_b) as f64 / 2.0;
18053 let candidate_mean = (candidate_a + candidate_b) as f64 / 2.0;
18054 println!(
18055 "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}",
18056 spread(former_a, former_b),
18057 spread(candidate_a, candidate_b),
18058 former_mean / candidate_mean,
18059 body_started.elapsed().as_secs_f64()
18060 );
18061 }
18062
18063 #[test]
18064 fn nansem_empty_returns_null() {
18065 assert!(super::nansem(&[], 1).is_missing());
18066 assert!(super::nansem(&[Scalar::Float64(1.0)], 1).is_missing());
18067 }
18068
18069 #[test]
18070 fn nanptp_returns_max_minus_min() {
18071 let values = vec![
18072 Scalar::Float64(3.0),
18073 Scalar::Null(NullKind::NaN),
18074 Scalar::Float64(7.0),
18075 Scalar::Float64(1.0),
18076 ];
18077 assert_eq!(super::nanptp(&values), Scalar::Float64(6.0));
18078 }
18079
18080 #[test]
18081 fn nanptp_empty_returns_null() {
18082 assert!(super::nanptp(&[]).is_missing());
18083 assert!(super::nanptp(&[Scalar::Null(NullKind::NaN)]).is_missing());
18084 }
18085
18086 #[test]
18087 fn nanptp_timedelta64_preserves_dtype_u2g0r() {
18088 let one_hour: i64 = 3_600 * 1_000_000_000;
18090 let values = vec![
18091 Scalar::Timedelta64(one_hour),
18092 Scalar::Timedelta64(5 * one_hour),
18093 Scalar::Timedelta64(2 * one_hour),
18094 ];
18095 assert_eq!(super::nanptp(&values), Scalar::Timedelta64(4 * one_hour));
18096 }
18097
18098 #[test]
18099 fn nanptp_matches_numeric_and_timedelta_oracle_affjt() {
18100 fn next(seed: &mut u64) -> u64 {
18103 *seed = seed
18104 .wrapping_mul(3202034522624059733)
18105 .wrapping_add(4354685564936845319);
18106 *seed
18107 }
18108
18109 fn expected_numeric(values: &[Scalar]) -> Scalar {
18110 let mut lo = f64::INFINITY;
18111 let mut hi = f64::NEG_INFINITY;
18112 let mut seen = false;
18113 for value in values {
18114 if value.is_missing() {
18115 continue;
18116 }
18117 if let Ok(value) = value.to_f64() {
18118 seen = true;
18119 lo = lo.min(value);
18120 hi = hi.max(value);
18121 }
18122 }
18123 if seen {
18124 Scalar::Float64(hi - lo)
18125 } else {
18126 Scalar::Null(NullKind::NaN)
18127 }
18128 }
18129
18130 fn expected_timedelta(values: &[Scalar]) -> Scalar {
18131 let mut lo = i64::MAX;
18132 let mut hi = i64::MIN;
18133 let mut seen = false;
18134 for value in values {
18135 if let Scalar::Timedelta64(ns) = value
18136 && !value.is_missing()
18137 {
18138 seen = true;
18139 lo = lo.min(*ns);
18140 hi = hi.max(*ns);
18141 }
18142 }
18143 if seen {
18144 Scalar::Timedelta64(hi - lo)
18145 } else {
18146 Scalar::Null(NullKind::NaN)
18147 }
18148 }
18149
18150 fn assert_ptp(case: usize, family: &str, values: &[Scalar], expected: Scalar) {
18151 let actual = super::nanptp(values);
18152 assert!(
18153 actual.semantic_eq(&expected),
18154 "case={case} family={family}: expected {expected:?}, got {actual:?} for {values:?}"
18155 );
18156 }
18157
18158 assert_ptp(
18159 usize::MAX,
18160 "numeric_all_missing",
18161 &[Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)],
18162 Scalar::Null(NullKind::NaN),
18163 );
18164 assert_ptp(
18165 usize::MAX - 1,
18166 "timedelta_all_missing",
18167 &[Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)],
18168 Scalar::Null(NullKind::NaN),
18169 );
18170 let beyond_f64_exact_ns = 200 * Timedelta::NANOS_PER_DAY;
18171 assert_ptp(
18172 usize::MAX - 2,
18173 "timedelta_one_ns_range_beyond_f64_exactness",
18174 &[
18175 Scalar::Timedelta64(beyond_f64_exact_ns),
18176 Scalar::Timedelta64(beyond_f64_exact_ns - 1),
18177 Scalar::Timedelta64(Timedelta::NAT),
18178 ],
18179 Scalar::Timedelta64(1),
18180 );
18181
18182 let mut seed = 0xa22f_17ed_57a7_15e5_u64;
18183 for case in 0..260 {
18184 let len = (next(&mut seed) % 83 + 1) as usize;
18185
18186 let mut numeric = Vec::with_capacity(len);
18187 numeric.push(Scalar::Int64(case as i64 - 130));
18188 for _ in 1..len {
18189 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
18190 numeric.push(match next(&mut seed) % 9 {
18191 0 => Scalar::Null(NullKind::Null),
18192 1 => Scalar::Null(NullKind::NaN),
18193 2 => Scalar::Float64(f64::NAN),
18194 3 => Scalar::Bool(raw & 1 == 0),
18195 4 => Scalar::Int64(raw),
18196 5 => Scalar::Float64(raw as f64 / 53.0),
18197 6 => Scalar::Float64(0.0),
18198 7 => Scalar::Float64(-0.0),
18199 _ => Scalar::Float64(raw.signum() as f64 * f64::INFINITY),
18200 });
18201 }
18202 assert_ptp(case, "numeric", &numeric, expected_numeric(&numeric));
18203
18204 let mut timedeltas = Vec::with_capacity(len);
18205 timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
18206 for _ in 1..len {
18207 let raw = (next(&mut seed) % 10_001) as i64 - 5_000;
18208 timedeltas.push(match next(&mut seed) % 7 {
18209 0 => Scalar::Null(NullKind::Null),
18210 1 => Scalar::Timedelta64(i64::MIN),
18211 _ => Scalar::Timedelta64(raw),
18212 });
18213 }
18214 assert_ptp(
18215 case,
18216 "timedelta",
18217 &timedeltas,
18218 expected_timedelta(&timedeltas),
18219 );
18220 }
18221 }
18222
18223 #[test]
18224 fn nanargmax_nanargmin_timedelta64_compare_by_ns_ql1t5() {
18225 let one_hour: i64 = 3_600 * 1_000_000_000;
18228 let values = vec![
18229 Scalar::Timedelta64(2 * one_hour),
18230 Scalar::Timedelta64(5 * one_hour),
18231 Scalar::Timedelta64(one_hour),
18232 Scalar::Timedelta64(3 * one_hour),
18233 ];
18234 assert_eq!(super::nanargmax(&values), Some(1));
18235 assert_eq!(super::nanargmin(&values), Some(2));
18236 }
18237
18238 #[test]
18239 fn nanprod_timedelta64_returns_null_szq6a() {
18240 let one_hour: i64 = 3_600 * 1_000_000_000;
18244 let values = vec![
18245 Scalar::Timedelta64(2 * one_hour),
18246 Scalar::Timedelta64(3 * one_hour),
18247 ];
18248 assert!(super::nanprod(&values).is_missing());
18249 }
18250
18251 #[test]
18252 fn nanprod_matches_numeric_and_timedelta_oracle_9938h() {
18253 fn next(seed: &mut u64) -> u64 {
18256 *seed = seed
18257 .wrapping_mul(6364136223846793005)
18258 .wrapping_add(1442695040888963407);
18259 *seed
18260 }
18261
18262 fn expected_numeric(values: &[Scalar]) -> Scalar {
18263 let mut product = 1.0_f64;
18264 for value in values {
18265 if value.is_missing() {
18266 continue;
18267 }
18268 if let Ok(value) = value.to_f64() {
18269 product *= value;
18270 }
18271 }
18272 Scalar::Float64(product)
18273 }
18274
18275 fn expected_timedelta(values: &[Scalar]) -> Scalar {
18276 if values
18277 .iter()
18278 .any(|value| matches!(value, Scalar::Timedelta64(_)) && !value.is_missing())
18279 {
18280 Scalar::Null(NullKind::NaN)
18281 } else {
18282 Scalar::Float64(1.0)
18283 }
18284 }
18285
18286 fn assert_prod(case: usize, family: &str, values: &[Scalar], expected: Scalar) {
18287 let actual = super::nanprod(values);
18288 assert!(
18289 actual.semantic_eq(&expected),
18290 "case={case} family={family}: expected {expected:?}, got {actual:?} for {values:?}"
18291 );
18292 }
18293
18294 let all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
18295 assert_prod(
18296 usize::MAX,
18297 "numeric_all_missing",
18298 &all_missing,
18299 Scalar::Float64(1.0),
18300 );
18301
18302 let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
18303 assert_prod(
18304 usize::MAX - 1,
18305 "timedelta_all_missing",
18306 &td_all_missing,
18307 expected_timedelta(&td_all_missing),
18308 );
18309
18310 let mut seed = 0x6e0d_9938_a11c_0de5_u64;
18311 for case in 0..280 {
18312 let len = (next(&mut seed) % 89 + 1) as usize;
18313
18314 let mut numeric = Vec::with_capacity(len);
18315 numeric.push(Scalar::Int64((case % 17) as i64 - 8));
18316 for _ in 1..len {
18317 let raw = (next(&mut seed) % 2_001) as i64 - 1_000;
18318 numeric.push(match next(&mut seed) % 9 {
18319 0 => Scalar::Null(NullKind::Null),
18320 1 => Scalar::Null(NullKind::NaN),
18321 2 => Scalar::Float64(f64::NAN),
18322 3 => Scalar::Bool(raw & 1 == 0),
18323 4 => Scalar::Int64(raw % 19),
18324 5 => Scalar::Float64(raw as f64 / 97.0),
18325 6 => Scalar::Float64(0.0),
18326 7 => Scalar::Float64(-0.0),
18327 _ => Scalar::Float64(1.0),
18328 });
18329 }
18330 assert_prod(case, "numeric", &numeric, expected_numeric(&numeric));
18331
18332 let mut timedeltas = Vec::with_capacity(len);
18333 timedeltas.push(Scalar::Timedelta64(case as i64 - 140));
18334 for _ in 1..len {
18335 let raw = (next(&mut seed) % 10_001) as i64 - 5_000;
18336 timedeltas.push(match next(&mut seed) % 7 {
18337 0 => Scalar::Null(NullKind::Null),
18338 1 => Scalar::Timedelta64(i64::MIN),
18339 _ => Scalar::Timedelta64(raw),
18340 });
18341 }
18342 assert_prod(
18343 case,
18344 "timedelta",
18345 &timedeltas,
18346 expected_timedelta(&timedeltas),
18347 );
18348 }
18349 }
18350
18351 #[test]
18352 fn nanskew_symmetric_distribution_near_zero() {
18353 let values = vec![
18354 Scalar::Float64(1.0),
18355 Scalar::Float64(2.0),
18356 Scalar::Float64(3.0),
18357 Scalar::Float64(4.0),
18358 Scalar::Float64(5.0),
18359 ];
18360 let skew = super::nanskew(&values);
18362 assert!(matches!(skew, Scalar::Float64(_)));
18363 let Scalar::Float64(v) = skew else {
18364 return;
18365 };
18366 assert!(v.abs() < 1e-9);
18367 }
18368
18369 #[test]
18370 fn nanskew_too_few_values_returns_null() {
18371 assert!(super::nanskew(&[]).is_missing());
18372 assert!(super::nanskew(&[Scalar::Float64(1.0), Scalar::Float64(2.0)]).is_missing());
18373 }
18374
18375 #[test]
18376 fn nankurt_symmetric_uniform_distribution() {
18377 let values = vec![
18378 Scalar::Float64(1.0),
18379 Scalar::Float64(2.0),
18380 Scalar::Float64(3.0),
18381 Scalar::Float64(4.0),
18382 Scalar::Float64(5.0),
18383 ];
18384 let kurt = super::nankurt(&values);
18386 assert!(matches!(kurt, Scalar::Float64(_)));
18387 let Scalar::Float64(v) = kurt else {
18388 return;
18389 };
18390 assert!((v + 1.2).abs() < 1e-9);
18391 }
18392
18393 #[test]
18394 fn nankurt_too_few_values_returns_null() {
18395 let vals: Vec<Scalar> = (0..3).map(|i| Scalar::Float64(i as f64)).collect();
18396 assert!(super::nankurt(&vals).is_missing());
18397 }
18398
18399 #[test]
18400 fn nanskew_constant_series_returns_zero() {
18401 let values = vec![
18402 Scalar::Float64(5.0),
18403 Scalar::Float64(5.0),
18404 Scalar::Float64(5.0),
18405 ];
18406 assert_eq!(super::nanskew(&values), Scalar::Float64(0.0));
18407 assert_eq!(
18408 super::nankurt(&[
18409 Scalar::Float64(5.0),
18410 Scalar::Float64(5.0),
18411 Scalar::Float64(5.0),
18412 Scalar::Float64(5.0),
18413 ]),
18414 Scalar::Float64(0.0)
18415 );
18416 }
18417
18418 #[test]
18419 fn nanskew_nankurt_match_numeric_oracle_jr7zk() {
18420 fn next(seed: &mut u64) -> u64 {
18423 *seed = seed
18424 .wrapping_mul(2862933555777941757)
18425 .wrapping_add(3037000493);
18426 *seed
18427 }
18428
18429 fn samples(values: &[Scalar]) -> Vec<f64> {
18430 values
18431 .iter()
18432 .filter(|value| !value.is_missing())
18433 .filter_map(|value| value.to_f64().ok())
18434 .collect()
18435 }
18436
18437 fn expected_skew(values: &[Scalar]) -> Scalar {
18438 let samples = samples(values);
18439 let n = samples.len() as f64;
18440 if n < 3.0 {
18441 return Scalar::Null(NullKind::NaN);
18442 }
18443 let mean = samples.iter().sum::<f64>() / n;
18444 let m2 = samples
18445 .iter()
18446 .map(|value| (value - mean).powi(2))
18447 .sum::<f64>();
18448 let m3 = samples
18449 .iter()
18450 .map(|value| (value - mean).powi(3))
18451 .sum::<f64>();
18452 let s2 = m2 / (n - 1.0);
18453 if s2 == 0.0 {
18454 return Scalar::Float64(0.0);
18455 }
18456 Scalar::Float64((n / ((n - 1.0) * (n - 2.0))) * (m3 / s2.powf(1.5)))
18457 }
18458
18459 fn expected_kurt(values: &[Scalar]) -> Scalar {
18460 let samples = samples(values);
18461 let n = samples.len() as f64;
18462 if n < 4.0 {
18463 return Scalar::Null(NullKind::NaN);
18464 }
18465 let mean = samples.iter().sum::<f64>() / n;
18466 let m2 = samples
18467 .iter()
18468 .map(|value| (value - mean).powi(2))
18469 .sum::<f64>();
18470 let m4 = samples
18471 .iter()
18472 .map(|value| (value - mean).powi(4))
18473 .sum::<f64>();
18474 let s2 = m2 / (n - 1.0);
18475 if s2 == 0.0 {
18476 return Scalar::Float64(0.0);
18477 }
18478 let adj = (n * (n + 1.0)) / ((n - 1.0) * (n - 2.0) * (n - 3.0));
18479 let sub = (3.0 * (n - 1.0).powi(2)) / ((n - 2.0) * (n - 3.0));
18480 Scalar::Float64(adj * (m4 / (s2 * s2)) - sub)
18481 }
18482
18483 fn assert_moments(case: usize, values: &[Scalar]) {
18484 let expected_skew = expected_skew(values);
18485 let expected_kurt = expected_kurt(values);
18486 let actual_skew = super::nanskew(values);
18487 let actual_kurt = super::nankurt(values);
18488 assert!(
18489 actual_skew.semantic_eq(&expected_skew),
18490 "case={case}: expected skew {expected_skew:?}, got {actual_skew:?} for {values:?}"
18491 );
18492 assert!(
18493 actual_kurt.semantic_eq(&expected_kurt),
18494 "case={case}: expected kurt {expected_kurt:?}, got {actual_kurt:?} for {values:?}"
18495 );
18496 }
18497
18498 assert_moments(
18499 usize::MAX,
18500 &[Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)],
18501 );
18502 assert_moments(
18503 usize::MAX - 1,
18504 &[
18505 Scalar::Float64(7.0),
18506 Scalar::Float64(7.0),
18507 Scalar::Float64(7.0),
18508 Scalar::Float64(7.0),
18509 ],
18510 );
18511
18512 let mut seed = 0x5ce7_9a55_a11c_0de5_u64;
18513 for case in 0..260 {
18514 let len = (next(&mut seed) % 89 + 1) as usize;
18515 let mut values = Vec::with_capacity(len);
18516 if case % 11 == 0 {
18517 values.extend((0..len).map(|_| Scalar::Float64(3.0)));
18518 } else {
18519 values.push(Scalar::Float64(case as f64 / 19.0));
18520 for _ in 1..len {
18521 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
18522 values.push(match next(&mut seed) % 8 {
18523 0 => Scalar::Null(NullKind::Null),
18524 1 => Scalar::Null(NullKind::NaN),
18525 2 => Scalar::Float64(f64::NAN),
18526 3 => Scalar::Bool(raw & 1 == 0),
18527 4 => Scalar::Int64(raw % 251),
18528 5 => Scalar::Float64(raw as f64 / 83.0),
18529 6 => Scalar::Float64(0.0),
18530 _ => Scalar::Float64(-0.0),
18531 });
18532 }
18533 }
18534 assert_moments(case, &values);
18535 }
18536 }
18537
18538 #[test]
18541 fn interval_default_closed_is_right() {
18542 assert_eq!(IntervalClosed::default(), IntervalClosed::Right);
18543 }
18544
18545 #[test]
18546 fn interval_left_and_right_closed_helpers() {
18547 assert!(IntervalClosed::Left.left_closed());
18548 assert!(!IntervalClosed::Left.right_closed());
18549 assert!(!IntervalClosed::Right.left_closed());
18550 assert!(IntervalClosed::Right.right_closed());
18551 assert!(IntervalClosed::Both.left_closed());
18552 assert!(IntervalClosed::Both.right_closed());
18553 assert!(!IntervalClosed::Neither.left_closed());
18554 assert!(!IntervalClosed::Neither.right_closed());
18555 }
18556
18557 #[test]
18558 fn interval_display_matches_pandas_notation() {
18559 assert_eq!(
18560 Interval::new(0.0, 5.0, IntervalClosed::Right).to_string(),
18561 "(0.0, 5.0]"
18562 );
18563 assert_eq!(
18564 Interval::new(0.0, 5.0, IntervalClosed::Left).to_string(),
18565 "[0.0, 5.0)"
18566 );
18567 assert_eq!(
18568 Interval::new(0.0, 5.0, IntervalClosed::Both).to_string(),
18569 "[0.0, 5.0]"
18570 );
18571 assert_eq!(
18572 Interval::new(0.0, 5.0, IntervalClosed::Neither).to_string(),
18573 "(0.0, 5.0)"
18574 );
18575 assert_eq!(
18576 Interval::new(2.5, 3.5, IntervalClosed::Right).to_string(),
18577 "(2.5, 3.5]"
18578 );
18579 assert_eq!(
18580 Interval::new(-1.0, 0.0, IntervalClosed::Right).to_string(),
18581 "(-1.0, 0.0]"
18582 );
18583 assert_eq!(
18584 Interval::new(1e20, 2e20, IntervalClosed::Right).to_string(),
18585 "(1e+20, 2e+20]"
18586 );
18587 }
18588
18589 #[test]
18590 fn interval_length_and_mid() {
18591 let i = Interval::new(2.0, 10.0, IntervalClosed::Right);
18592 assert_eq!(i.length(), 8.0);
18593 assert_eq!(i.mid(), 6.0);
18594 }
18595
18596 #[test]
18597 fn interval_contains_matches_closed_policy() {
18598 let right = Interval::new(0.0, 5.0, IntervalClosed::Right);
18599 assert!(!right.contains(0.0));
18600 assert!(right.contains(2.5));
18601 assert!(right.contains(5.0));
18602
18603 let left = Interval::new(0.0, 5.0, IntervalClosed::Left);
18604 assert!(left.contains(0.0));
18605 assert!(left.contains(2.5));
18606 assert!(!left.contains(5.0));
18607
18608 let both = Interval::new(0.0, 5.0, IntervalClosed::Both);
18609 assert!(both.contains(0.0));
18610 assert!(both.contains(5.0));
18611
18612 let neither = Interval::new(0.0, 5.0, IntervalClosed::Neither);
18613 assert!(!neither.contains(0.0));
18614 assert!(!neither.contains(5.0));
18615 assert!(neither.contains(2.5));
18616 }
18617
18618 #[test]
18619 fn interval_contains_nan_returns_false() {
18620 let i = Interval::new(0.0, 10.0, IntervalClosed::Both);
18621 assert!(!i.contains(f64::NAN));
18622 }
18623
18624 #[test]
18625 fn interval_is_empty_matches_pandas() {
18626 assert!(Interval::new(3.0, 3.0, IntervalClosed::Right).is_empty());
18628 assert!(Interval::new(3.0, 3.0, IntervalClosed::Left).is_empty());
18629 assert!(Interval::new(3.0, 3.0, IntervalClosed::Neither).is_empty());
18630 assert!(!Interval::new(3.0, 3.0, IntervalClosed::Both).is_empty());
18632 assert!(!Interval::new(0.0, 5.0, IntervalClosed::Right).is_empty());
18634 }
18635
18636 #[test]
18637 fn interval_overlaps_disjoint_returns_false() {
18638 let a = Interval::new(0.0, 1.0, IntervalClosed::Right);
18639 let b = Interval::new(2.0, 3.0, IntervalClosed::Right);
18640 assert!(!a.overlaps(&b));
18641 assert!(!b.overlaps(&a));
18642 }
18643
18644 #[test]
18645 fn interval_overlaps_nested_returns_true() {
18646 let outer = Interval::new(0.0, 10.0, IntervalClosed::Right);
18647 let inner = Interval::new(3.0, 7.0, IntervalClosed::Right);
18648 assert!(outer.overlaps(&inner));
18649 assert!(inner.overlaps(&outer));
18650 }
18651
18652 #[test]
18653 fn interval_overlaps_touching_respects_closed_policy() {
18654 let right_right = (
18656 Interval::new(0.0, 1.0, IntervalClosed::Right),
18657 Interval::new(1.0, 2.0, IntervalClosed::Right),
18658 );
18659 assert!(!right_right.0.overlaps(&right_right.1));
18661
18662 let both_both = (
18664 Interval::new(0.0, 1.0, IntervalClosed::Both),
18665 Interval::new(1.0, 2.0, IntervalClosed::Both),
18666 );
18667 assert!(both_both.0.overlaps(&both_both.1));
18668 }
18669
18670 #[test]
18671 fn interval_roundtrips_through_serde_json() {
18672 let i = Interval::new(1.5, 3.25, IntervalClosed::Both);
18673 let json = serde_json::to_string(&i).expect("serialize");
18674 let back: Interval = serde_json::from_str(&json).expect("deserialize");
18675 assert_eq!(i, back);
18676 }
18677
18678 #[test]
18679 fn interval_serde_default_closed_is_right_when_missing() {
18680 let back: Interval =
18682 serde_json::from_str(r#"{"left":0.0,"right":5.0}"#).expect("deserialize");
18683 assert_eq!(back.closed, IntervalClosed::Right);
18684 }
18685
18686 #[test]
18689 fn period_freq_parses_canonical_aliases() {
18690 assert_eq!(PeriodFreq::parse("A"), Some(PeriodFreq::ANNUAL));
18691 assert_eq!(PeriodFreq::parse("Y"), Some(PeriodFreq::ANNUAL));
18692 assert_eq!(PeriodFreq::parse("Q"), Some(PeriodFreq::QUARTERLY));
18693 assert_eq!(PeriodFreq::parse("M"), Some(PeriodFreq::Monthly));
18694 assert_eq!(PeriodFreq::parse("W"), Some(PeriodFreq::WEEKLY));
18695 assert_eq!(PeriodFreq::parse("D"), Some(PeriodFreq::Daily));
18696 assert_eq!(PeriodFreq::parse("B"), Some(PeriodFreq::Business));
18697 assert_eq!(PeriodFreq::parse("H"), Some(PeriodFreq::Hourly));
18698 assert_eq!(PeriodFreq::parse("T"), Some(PeriodFreq::Minutely));
18699 assert_eq!(PeriodFreq::parse("min"), Some(PeriodFreq::Minutely));
18700 assert_eq!(PeriodFreq::parse("S"), Some(PeriodFreq::Secondly));
18701 }
18702
18703 #[test]
18704 fn period_freq_parse_is_case_insensitive() {
18705 assert_eq!(PeriodFreq::parse("quarterly"), Some(PeriodFreq::QUARTERLY));
18706 assert_eq!(PeriodFreq::parse("MONTHLY"), Some(PeriodFreq::Monthly));
18707 }
18708
18709 #[test]
18710 fn period_freq_rejects_unknown_aliases() {
18711 assert_eq!(PeriodFreq::parse("nanosec"), None);
18712 assert_eq!(PeriodFreq::parse(""), None);
18713 assert_eq!(PeriodFreq::parse("xyz"), None);
18714 }
18715
18716 #[test]
18717 fn period_freq_alias_roundtrip() {
18718 for freq in [
18719 PeriodFreq::ANNUAL,
18720 PeriodFreq::QUARTERLY,
18721 PeriodFreq::Monthly,
18722 PeriodFreq::WEEKLY,
18723 PeriodFreq::Daily,
18724 PeriodFreq::Business,
18725 PeriodFreq::Hourly,
18726 PeriodFreq::Minutely,
18727 PeriodFreq::Secondly,
18728 PeriodFreq::Milliseconds,
18729 PeriodFreq::Microseconds,
18730 PeriodFreq::Nanoseconds,
18731 ] {
18732 assert_eq!(PeriodFreq::parse(&freq.alias()), Some(freq));
18733 }
18734 }
18735
18736 #[test]
18741 fn anchored_period_freqs_parse_print_and_shift_39h5n() {
18742 for month in 1..=12_u8 {
18743 for freq in [PeriodFreq::Annual(month), PeriodFreq::Quarterly(month)] {
18744 assert_eq!(PeriodFreq::parse(&freq.alias()), Some(freq));
18745 }
18746 }
18747 for day in 0..7_u8 {
18748 assert_eq!(
18749 PeriodFreq::parse(&PeriodFreq::Weekly(day).alias()),
18750 Some(PeriodFreq::Weekly(day))
18751 );
18752 }
18753 assert_eq!(PeriodFreq::parse("Y-JUN"), Some(PeriodFreq::Annual(6)));
18754 assert_eq!(PeriodFreq::parse("A-JUN"), Some(PeriodFreq::Annual(6)));
18755 assert_eq!(PeriodFreq::parse("q-jan"), Some(PeriodFreq::Quarterly(1)));
18756 assert_eq!(PeriodFreq::parse("W-MON"), Some(PeriodFreq::Weekly(0)));
18757 assert_eq!(PeriodFreq::parse("Q-DEC"), Some(PeriodFreq::QUARTERLY));
18758 assert_eq!(PeriodFreq::parse("Q-XYZ"), None);
18760 assert_eq!(PeriodFreq::parse("M-JAN"), None);
18761 assert_eq!(PeriodFreq::parse("W-JAN"), None);
18762 assert_eq!(PeriodFreq::Annual(6).fiscal_month_shift(), 6);
18763 assert_eq!(PeriodFreq::Quarterly(1).fiscal_month_shift(), 11);
18764 assert_eq!(PeriodFreq::QUARTERLY.fiscal_month_shift(), 0);
18765 assert_eq!(PeriodFreq::Weekly(0).week_start_shift(), 1);
18766 assert_eq!(PeriodFreq::WEEKLY.week_start_shift(), 0);
18767 assert_eq!(
18768 Period::new(2827, PeriodFreq::Weekly(0)).to_string(),
18769 "2024-02-27/2024-03-04"
18770 );
18771 assert_eq!(
18772 Period::new(2826, PeriodFreq::Weekly(5)).to_string(),
18773 "2024-02-25/2024-03-02"
18774 );
18775 assert_eq!(
18776 Period::new(220, PeriodFreq::Quarterly(1)).to_string(),
18777 "2025Q1"
18778 );
18779 }
18780
18781 #[test]
18785 fn period_freq_subsecond_units_match_pandas() {
18786 assert_eq!(PeriodFreq::Milliseconds.alias(), "ms");
18788 assert_eq!(PeriodFreq::Microseconds.alias(), "us");
18789 assert_eq!(PeriodFreq::Nanoseconds.alias(), "ns");
18790 assert_eq!(PeriodFreq::Milliseconds.resolution(), Some("millisecond"));
18791 assert_eq!(PeriodFreq::Microseconds.resolution(), Some("microsecond"));
18792 assert_eq!(PeriodFreq::Nanoseconds.resolution(), Some("nanosecond"));
18793
18794 assert_eq!(PeriodFreq::parse("ms"), Some(PeriodFreq::Milliseconds));
18797 assert_eq!(PeriodFreq::parse("Ms"), Some(PeriodFreq::Milliseconds));
18798 assert_eq!(PeriodFreq::parse("mS"), Some(PeriodFreq::Milliseconds));
18799 assert_eq!(PeriodFreq::parse("MS"), None);
18800 assert_eq!(PeriodFreq::parse("us"), Some(PeriodFreq::Microseconds));
18802 assert_eq!(PeriodFreq::parse("US"), Some(PeriodFreq::Microseconds));
18803 assert_eq!(PeriodFreq::parse("ns"), Some(PeriodFreq::Nanoseconds));
18804 assert_eq!(PeriodFreq::parse("NS"), Some(PeriodFreq::Nanoseconds));
18805
18806 assert_eq!(
18809 Period::new(1_710_498_645_123, PeriodFreq::Milliseconds).calendar_string(),
18810 "2024-03-15 10:30:45.123"
18811 );
18812 assert_eq!(
18813 Period::new(1_710_498_645_123_456, PeriodFreq::Microseconds).calendar_string(),
18814 "2024-03-15 10:30:45.123456"
18815 );
18816 assert_eq!(
18817 Period::new(1_710_498_645_123_456_789, PeriodFreq::Nanoseconds).calendar_string(),
18818 "2024-03-15 10:30:45.123456789"
18819 );
18820
18821 assert_eq!(
18825 Period::new(0, PeriodFreq::Milliseconds).calendar_string(),
18826 "1970-01-01 00:00:00.000"
18827 );
18828 assert_eq!(
18829 Period::new(-1, PeriodFreq::Milliseconds).calendar_string(),
18830 "1969-12-31 23:59:59.999"
18831 );
18832 assert_eq!(
18833 Period::new(-1_000, PeriodFreq::Microseconds).calendar_string(),
18834 "1969-12-31 23:59:59.999000"
18835 );
18836 assert_eq!(
18837 Period::new(-999_999, PeriodFreq::Nanoseconds).calendar_string(),
18838 "1969-12-31 23:59:59.999000001"
18839 );
18840 }
18841
18842 #[test]
18843 fn period_freq_anchored_aliases_are_pandas_canonical_h2wiv() {
18844 assert_eq!(PeriodFreq::ANNUAL.alias(), "Y-DEC");
18845 assert_eq!(PeriodFreq::QUARTERLY.alias(), "Q-DEC");
18846 assert_eq!(PeriodFreq::WEEKLY.alias(), "W-SUN");
18847
18848 assert_eq!(PeriodFreq::parse("A"), Some(PeriodFreq::ANNUAL));
18849 assert_eq!(PeriodFreq::parse("Y"), Some(PeriodFreq::ANNUAL));
18850 assert_eq!(PeriodFreq::parse("Y-DEC"), Some(PeriodFreq::ANNUAL));
18851 assert_eq!(PeriodFreq::parse("Q"), Some(PeriodFreq::QUARTERLY));
18852 assert_eq!(PeriodFreq::parse("Q-DEC"), Some(PeriodFreq::QUARTERLY));
18853 assert_eq!(PeriodFreq::parse("W"), Some(PeriodFreq::WEEKLY));
18854 assert_eq!(PeriodFreq::parse("W-SUN"), Some(PeriodFreq::WEEKLY));
18855 }
18856
18857 #[test]
18858 fn period_freq_intraday_aliases_are_pandas_canonical_8kfdo() {
18859 assert_eq!(PeriodFreq::Hourly.alias(), "h");
18860 assert_eq!(PeriodFreq::Minutely.alias(), "min");
18861 assert_eq!(PeriodFreq::Secondly.alias(), "s");
18862
18863 assert_eq!(PeriodFreq::parse("H"), Some(PeriodFreq::Hourly));
18864 assert_eq!(PeriodFreq::parse("T"), Some(PeriodFreq::Minutely));
18865 assert_eq!(PeriodFreq::parse("S"), Some(PeriodFreq::Secondly));
18866 }
18867
18868 #[test]
18872 fn period_freq_resolution_is_the_component_word_not_the_alias() {
18873 assert_eq!(PeriodFreq::ANNUAL.resolution(), Some("year"));
18874 assert_eq!(PeriodFreq::QUARTERLY.resolution(), Some("quarter"));
18875 assert_eq!(PeriodFreq::Monthly.resolution(), Some("month"));
18876 assert_eq!(PeriodFreq::Daily.resolution(), Some("day"));
18877 assert_eq!(PeriodFreq::Hourly.resolution(), Some("hour"));
18878 assert_eq!(PeriodFreq::Minutely.resolution(), Some("minute"));
18879 assert_eq!(PeriodFreq::Secondly.resolution(), Some("second"));
18880
18881 assert_eq!(PeriodFreq::WEEKLY.resolution(), None);
18883 assert_eq!(PeriodFreq::Business.resolution(), None);
18884
18885 for freq in [
18890 PeriodFreq::ANNUAL,
18891 PeriodFreq::QUARTERLY,
18892 PeriodFreq::Monthly,
18893 PeriodFreq::WEEKLY,
18894 PeriodFreq::Daily,
18895 PeriodFreq::Business,
18896 PeriodFreq::Hourly,
18897 PeriodFreq::Minutely,
18898 PeriodFreq::Secondly,
18899 ] {
18900 assert_ne!(
18901 Some(freq.alias().as_str()),
18902 freq.resolution(),
18903 "{freq:?} reports its alias as its resolution again"
18904 );
18905 }
18906 }
18907
18908 #[test]
18909 fn period_scalar_accessors_match_pandas_star8() {
18910 let period = Period::new(600, PeriodFreq::Monthly);
18911
18912 assert_eq!(period.ordinal(), 600);
18913 assert_eq!(period.freq(), PeriodFreq::Monthly);
18914 assert_eq!(period.freqstr(), "M");
18915 }
18916
18917 #[test]
18918 fn period_multiplied_frequencies_parse_and_roundtrip_tus8r() {
18919 for (alias, canonical, base, multiplier) in [
18920 ("2D", "2D", PeriodFreq::Daily, 2),
18921 ("+3H", "3h", PeriodFreq::Hourly, 3),
18922 ("15min", "15min", PeriodFreq::Minutely, 15),
18923 ("2W-FRI", "2W-FRI", PeriodFreq::Weekly(4), 2),
18924 ("2M", "2M", PeriodFreq::Monthly, 2),
18925 ("2Q-JAN", "2Q-JAN", PeriodFreq::Quarterly(1), 2),
18926 ("2Y-JUN", "2Y-JUN", PeriodFreq::Annual(6), 2),
18927 ("2B", "2B", PeriodFreq::Business, 2),
18928 ("2ms", "2ms", PeriodFreq::Milliseconds, 2),
18929 ("3us", "3us", PeriodFreq::Microseconds, 3),
18930 ("4ns", "4ns", PeriodFreq::Nanoseconds, 4),
18931 ] {
18932 let freq = PeriodFreq::parse(alias).expect("valid multiplied frequency");
18933 assert_eq!(freq.base(), base, "{alias}");
18934 assert_eq!(freq.multiplier(), multiplier, "{alias}");
18935 assert_eq!(freq.alias(), canonical, "{alias}");
18936 assert_eq!(PeriodFreq::parse(&freq.alias()), Some(freq));
18937 assert_eq!(freq.resolution(), None);
18938 let encoded = serde_json::to_string(&freq).expect("serializable frequency");
18939 assert_eq!(serde_json::from_str::<PeriodFreq>(&encoded).unwrap(), freq);
18940 }
18941 assert_eq!(PeriodFreq::parse("1D"), Some(PeriodFreq::Daily));
18942 for invalid in ["0D", "-1D", "2MS", "2 3D", "2", "9223372036854775808D"] {
18943 assert_eq!(PeriodFreq::parse(invalid), None, "{invalid}");
18944 }
18945 assert!(
18946 serde_json::from_str::<PeriodFreq>(r#"{"MULTIPLE":{"unit":"DAILY","count":0}}"#,)
18947 .is_err()
18948 );
18949 }
18950
18951 #[test]
18955 fn period_multiplied_boundaries_and_labels_match_pandas_tus8r() {
18956 let nanos = 1_709_128_079_123_456_789;
18957 for (alias, ordinal, label, start, end) in [
18958 (
18959 "2D",
18960 19_781,
18961 "2024-02-28",
18962 1_709_078_400_000_000_000,
18963 1_709_251_199_999_999_999,
18964 ),
18965 (
18966 "3h",
18967 474_757,
18968 "2024-02-28 13:00",
18969 1_709_125_200_000_000_000,
18970 1_709_135_999_999_999_999,
18971 ),
18972 (
18973 "15min",
18974 28_485_467,
18975 "2024-02-28 13:47",
18976 1_709_128_020_000_000_000,
18977 1_709_128_919_999_999_999,
18978 ),
18979 (
18980 "2W-FRI",
18981 2_826,
18982 "2024-02-24/2024-03-01",
18983 1_708_732_800_000_000_000,
18984 1_709_942_399_999_999_999,
18985 ),
18986 (
18987 "2M",
18988 649,
18989 "2024-02",
18990 1_706_745_600_000_000_000,
18991 1_711_929_599_999_999_999,
18992 ),
18993 (
18994 "2Q-JAN",
18995 220,
18996 "2025Q1",
18997 1_706_745_600_000_000_000,
18998 1_722_470_399_999_999_999,
18999 ),
19000 (
19001 "2Y-JUN",
19002 54,
19003 "2024",
19004 1_688_169_600_000_000_000,
19005 1_751_327_999_999_999_999,
19006 ),
19007 (
19008 "2B",
19009 14_129,
19010 "2024-02-28",
19011 1_709_078_400_000_000_000,
19012 1_709_251_199_999_999_999,
19013 ),
19014 (
19015 "2ms",
19016 1_709_128_079_123,
19017 "2024-02-28 13:47:59.123",
19018 1_709_128_079_123_000_000,
19019 1_709_128_079_124_999_999,
19020 ),
19021 (
19022 "3us",
19023 1_709_128_079_123_456,
19024 "2024-02-28 13:47:59.123456",
19025 1_709_128_079_123_456_000,
19026 1_709_128_079_123_458_999,
19027 ),
19028 (
19029 "4ns",
19030 nanos,
19031 "2024-02-28 13:47:59.123456789",
19032 nanos,
19033 nanos + 3,
19034 ),
19035 ] {
19036 let freq = PeriodFreq::parse(alias).expect("valid multiplied frequency");
19037 let period = Period::from_timestamp_nanos(nanos, freq).expect("in-range timestamp");
19038 assert_eq!(period.ordinal, ordinal, "{alias}");
19039 assert_eq!(period.to_string(), label, "{alias}");
19040 assert_eq!(period.start_nanos(), Some(start), "{alias}");
19041 assert_eq!(period.end_nanos(), Some(end), "{alias}");
19042 assert_eq!(period.shift(1).ordinal, ordinal + freq.multiplier());
19043 assert_eq!(period.shift(-1).ordinal, ordinal - freq.multiplier());
19044 assert_eq!(period.shift(1).diff(&period), Some(freq.multiplier()));
19045 assert_eq!(
19046 period.asfreq(alias).unwrap().ordinal,
19047 ordinal + freq.multiplier() - 1
19048 );
19049 assert_eq!(period.asfreq_with_how(alias, "start").unwrap(), period);
19050 }
19051
19052 let business = Period::new(14_091, PeriodFreq::parse("2B").unwrap());
19055 assert_eq!(business.end_nanos(), Some(1_704_758_399_999_999_999));
19056 assert_eq!(business.shift(1).to_string(), "2024-01-09");
19057 let month = Period::new(649, PeriodFreq::parse("2M").unwrap());
19058 assert_eq!(
19059 (month.year(), month.month(), month.day()),
19060 (Some(2024), Some(2), Some(29))
19061 );
19062 let quarter = Period::new(220, PeriodFreq::parse("2Q-JAN").unwrap());
19063 assert_eq!(
19064 (quarter.year(), quarter.quarter(), quarter.qyear()),
19065 (Some(2024), Some(1), Some(2025))
19066 );
19067 }
19068
19069 #[test]
19070 fn period_multiplied_ranges_keep_negative_ordinals_and_nat_tus8r() {
19071 let freq = PeriodFreq::parse("3h").unwrap();
19072 let before_epoch = Period::from_timestamp_nanos(-1, freq).unwrap();
19073 assert_eq!(before_epoch.ordinal, -1);
19074 assert_eq!(before_epoch.start_nanos(), Some(-3_600_000_000_000));
19075 assert_eq!(before_epoch.end_nanos(), Some(7_199_999_999_999));
19076 assert_eq!(
19077 super::period_range(before_epoch, 3)
19078 .iter()
19079 .map(|period| period.ordinal)
19080 .collect::<Vec<_>>(),
19081 vec![-1, 2, 5],
19082 );
19083 assert!(super::period_range(before_epoch, 0).is_empty());
19084 let nat = Period::new(i64::MIN, freq);
19085 assert!(nat.shift(1).is_nat());
19086 assert!(nat.asfreq("2D").unwrap().is_nat());
19087 assert_eq!(nat.end_nanos(), None);
19088 assert_eq!(Period::new(i64::MAX, freq).end_nanos(), None);
19089 assert_eq!(Period::new(-100, freq).shift(i64::MAX).ordinal, i64::MAX);
19090 }
19091
19092 #[test]
19093 fn period_parse_common_pandas_ordinals_avm08() {
19094 assert_eq!(
19095 Period::parse("2024").unwrap(),
19096 Period::new(54, PeriodFreq::ANNUAL)
19097 );
19098 assert_eq!(
19099 Period::parse("2024Q1").unwrap(),
19100 Period::new(216, PeriodFreq::QUARTERLY)
19101 );
19102 assert_eq!(
19103 Period::parse("2024-01").unwrap(),
19104 Period::new(648, PeriodFreq::Monthly)
19105 );
19106 assert_eq!(
19107 Period::parse("2024-01-15").unwrap(),
19108 Period::new(19_737, PeriodFreq::Daily)
19109 );
19110 assert!(Period::parse("216").is_err());
19111 }
19112
19113 #[test]
19114 fn period_shift_advances_ordinal() {
19115 let q1 = Period::new(216, PeriodFreq::QUARTERLY);
19116 let q2 = q1.shift(1);
19117 assert_eq!(q2.ordinal, 217);
19118 assert_eq!(q2.freq, PeriodFreq::QUARTERLY);
19119 let q0 = q1.shift(-1);
19120 assert_eq!(q0.ordinal, 215);
19121 }
19122
19123 #[test]
19124 fn period_shift_saturates_on_overflow() {
19125 let p = Period::new(i64::MAX - 2, PeriodFreq::Daily);
19126 assert_eq!(p.shift(100).ordinal, i64::MAX);
19127 let p = Period::new(i64::MIN + 2, PeriodFreq::Daily);
19128 assert_eq!(p.shift(-100).ordinal, i64::MIN);
19129 }
19130
19131 #[test]
19132 fn period_diff_returns_period_count() {
19133 let a = Period::new(216, PeriodFreq::QUARTERLY);
19134 let b = Period::new(220, PeriodFreq::QUARTERLY);
19135 assert_eq!(b.diff(&a), Some(4));
19136 assert_eq!(a.diff(&b), Some(-4));
19137 }
19138
19139 #[test]
19140 fn period_diff_rejects_mismatched_freq() {
19141 let monthly = Period::new(100, PeriodFreq::Monthly);
19142 let quarterly = Period::new(100, PeriodFreq::QUARTERLY);
19143 assert_eq!(monthly.diff(&quarterly), None);
19144 assert_eq!(quarterly.diff(&monthly), None);
19145 }
19146
19147 #[test]
19148 fn period_cmp_same_freq_respects_ordinal_order() {
19149 use std::cmp::Ordering;
19150 let a = Period::new(10, PeriodFreq::Monthly);
19151 let b = Period::new(20, PeriodFreq::Monthly);
19152 assert_eq!(a.cmp_same_freq(&b), Some(Ordering::Less));
19153 assert_eq!(b.cmp_same_freq(&a), Some(Ordering::Greater));
19154 assert_eq!(a.cmp_same_freq(&a), Some(Ordering::Equal));
19155 }
19156
19157 #[test]
19158 fn period_cmp_cross_freq_returns_none() {
19159 let m = Period::new(1, PeriodFreq::Monthly);
19160 let q = Period::new(1, PeriodFreq::QUARTERLY);
19161 assert_eq!(m.cmp_same_freq(&q), None);
19162 }
19163
19164 #[test]
19165 fn period_arithmetic_matches_seeded_oracles_bac28() {
19166 use std::cmp::Ordering;
19167
19168 fn next(seed: &mut u64) -> u64 {
19169 *seed = seed
19170 .wrapping_mul(2862933555777941757)
19171 .wrapping_add(3037000493);
19172 *seed
19173 }
19174
19175 fn freq_for(raw: u64) -> PeriodFreq {
19176 match raw % 12 {
19179 0 => PeriodFreq::ANNUAL,
19180 1 => PeriodFreq::QUARTERLY,
19181 2 => PeriodFreq::Monthly,
19182 3 => PeriodFreq::WEEKLY,
19183 4 => PeriodFreq::Daily,
19184 5 => PeriodFreq::Business,
19185 6 => PeriodFreq::Hourly,
19186 7 => PeriodFreq::Minutely,
19187 8 => PeriodFreq::Secondly,
19188 9 => PeriodFreq::Milliseconds,
19189 10 => PeriodFreq::Microseconds,
19190 _ => PeriodFreq::Nanoseconds,
19191 }
19192 }
19193
19194 fn different_freq(freq: PeriodFreq) -> PeriodFreq {
19195 match freq {
19196 PeriodFreq::Annual(_) => PeriodFreq::QUARTERLY,
19197 PeriodFreq::Quarterly(_) => PeriodFreq::Monthly,
19198 PeriodFreq::Monthly => PeriodFreq::WEEKLY,
19199 PeriodFreq::Weekly(_) => PeriodFreq::Daily,
19200 PeriodFreq::Daily => PeriodFreq::Business,
19201 PeriodFreq::Business => PeriodFreq::Hourly,
19202 PeriodFreq::Hourly => PeriodFreq::Minutely,
19203 PeriodFreq::Minutely => PeriodFreq::Secondly,
19204 PeriodFreq::Secondly => PeriodFreq::Milliseconds,
19208 PeriodFreq::Milliseconds => PeriodFreq::Microseconds,
19209 PeriodFreq::Microseconds => PeriodFreq::Nanoseconds,
19210 PeriodFreq::Nanoseconds => PeriodFreq::ANNUAL,
19211 PeriodFreq::Multiple(_) => freq.base(),
19212 }
19213 }
19214
19215 fn assert_period_case(
19216 case: usize,
19217 freq: PeriodFreq,
19218 ordinal: i64,
19219 shift_by: i64,
19220 other_ordinal: i64,
19221 ) {
19222 let period = Period::new(ordinal, freq);
19223 let shifted = period.shift(shift_by);
19224 assert_eq!(
19225 shifted.ordinal,
19226 ordinal.saturating_add(shift_by),
19227 "case {case}: shift ordinal"
19228 );
19229 assert_eq!(shifted.freq, freq, "case {case}: shift freq");
19230
19231 let same_freq_other = Period::new(other_ordinal, freq);
19232 assert_eq!(
19233 period.diff(&same_freq_other),
19234 Some(ordinal.saturating_sub(other_ordinal)),
19235 "case {case}: same-freq diff"
19236 );
19237 assert_eq!(
19238 period.cmp_same_freq(&same_freq_other),
19239 Some(ordinal.cmp(&other_ordinal)),
19240 "case {case}: same-freq cmp"
19241 );
19242
19243 let cross_freq_other = Period::new(other_ordinal, different_freq(freq));
19244 assert_eq!(
19245 period.diff(&cross_freq_other),
19246 None,
19247 "case {case}: cross-freq diff"
19248 );
19249 assert_eq!(
19250 period.cmp_same_freq(&cross_freq_other),
19251 None,
19252 "case {case}: cross-freq cmp"
19253 );
19254 }
19255
19256 assert_period_case(usize::MAX, PeriodFreq::Daily, i64::MAX - 2, 10, i64::MIN);
19257 assert_period_case(
19258 usize::MAX - 1,
19259 PeriodFreq::Daily,
19260 i64::MIN + 2,
19261 -10,
19262 i64::MAX,
19263 );
19264 assert_eq!(
19265 Period::new(10, PeriodFreq::Monthly)
19266 .cmp_same_freq(&Period::new(10, PeriodFreq::Monthly)),
19267 Some(Ordering::Equal)
19268 );
19269
19270 let mut seed = 0xbac2_8d1f_0d1c_5eed_u64;
19271 for case in 0..260 {
19272 let freq = freq_for(next(&mut seed));
19273 let ordinal = match case % 53 {
19274 0 => i64::MAX - (next(&mut seed) % 8) as i64,
19275 1 => i64::MIN + (next(&mut seed) % 8) as i64,
19276 _ => (next(&mut seed) % 200_001) as i64 - 100_000,
19277 };
19278 let shift_by = match case % 47 {
19279 0 => 512,
19280 1 => -512,
19281 _ => (next(&mut seed) % 4097) as i64 - 2048,
19282 };
19283 let other_ordinal = match case % 41 {
19284 0 => i64::MAX,
19285 1 => i64::MIN,
19286 _ => (next(&mut seed) % 200_001) as i64 - 100_000,
19287 };
19288 assert_period_case(case, freq, ordinal, shift_by, other_ordinal);
19289 }
19290 }
19291
19292 #[test]
19293 fn period_display_is_pandas_calendar_string() {
19294 assert_eq!(
19296 Period::new(216, PeriodFreq::QUARTERLY).to_string(),
19297 "2024Q1"
19298 );
19299 assert_eq!(Period::new(54, PeriodFreq::ANNUAL).to_string(), "2024");
19301 assert_eq!(Period::new(650, PeriodFreq::Monthly).to_string(), "2024-03");
19303 assert_eq!(
19305 Period::new(fp_days("2024-01-15"), PeriodFreq::Daily).to_string(),
19306 "2024-01-15"
19307 );
19308 assert_eq!(
19309 Scalar::Period(Period::new(i64::MIN, PeriodFreq::Daily)).to_string(),
19310 "NaT"
19311 );
19312 }
19313
19314 #[test]
19322 fn weekly_and_business_periods_do_not_index_days() {
19323 for (ordinal, want) in [
19328 (0_i64, "1969-12-22/1969-12-28"),
19329 (1, "1969-12-29/1970-01-04"),
19330 (2829, "2024-03-11/2024-03-17"),
19331 (1540, "1999-06-28/1999-07-04"),
19332 (15237, "2261-12-30/2262-01-05"),
19333 (-1, "1969-12-15/1969-12-21"),
19335 (-2829, "1915-10-04/1915-10-10"),
19336 ] {
19337 assert_eq!(
19338 Period::new(ordinal, PeriodFreq::WEEKLY).to_string(),
19339 want,
19340 "weekly ordinal {ordinal}"
19341 );
19342 }
19343
19344 for (ordinal, want) in [
19348 (0_i64, "1970-01-01"), (1, "1970-01-02"), (2, "1970-01-05"), (3, "1970-01-06"),
19352 (4, "1970-01-07"),
19353 (5, "1970-01-08"),
19354 (14141, "2024-03-15"),
19355 (76179, "2262-01-01"),
19356 (7697, "1999-07-05"),
19359 (-1, "1969-12-31"),
19360 (-5, "1969-12-25"),
19361 (-6, "1969-12-24"),
19362 ] {
19363 assert_eq!(
19364 Period::new(ordinal, PeriodFreq::Business).to_string(),
19365 want,
19366 "business ordinal {ordinal}"
19367 );
19368 }
19369
19370 for ordinal in -400_i64..400 {
19374 let rendered = Period::new(ordinal, PeriodFreq::Business).to_string();
19375 let later = Period::new(ordinal + 5, PeriodFreq::Business).to_string();
19376 assert_ne!(rendered, later, "business ordinals must not repeat");
19377 }
19378
19379 assert_eq!(Period::new(i64::MIN, PeriodFreq::WEEKLY).to_string(), "NaT");
19380 assert_eq!(
19381 Period::new(i64::MIN, PeriodFreq::Business).to_string(),
19382 "NaT"
19383 );
19384 }
19385
19386 fn period_display_former_profile(period: &Period) -> String {
19387 let calendar = period.calendar_string();
19388 let mut rendered = String::new();
19389 rendered.push_str(&calendar);
19390 rendered
19391 }
19392
19393 fn measure_period_renderer(periods: &[Period], render: impl Fn(&Period) -> String) -> u128 {
19394 use std::{hint::black_box, time::Instant};
19395
19396 let started = Instant::now();
19397 let mut checksum = 0usize;
19398 for period in periods {
19399 let rendered = render(black_box(period));
19400 checksum = checksum.wrapping_add(rendered.len());
19401 drop(black_box(rendered));
19402 }
19403 black_box(checksum);
19404 started.elapsed().as_nanos()
19405 }
19406
19407 #[test]
19408 #[ignore = "release-only attribution probe for br-frankenpandas-6pqra"]
19409 fn profile_period_display_direct_sink_ab_6pqra() {
19410 const FREQUENCIES: [PeriodFreq; 9] = [
19411 PeriodFreq::ANNUAL,
19412 PeriodFreq::QUARTERLY,
19413 PeriodFreq::Monthly,
19414 PeriodFreq::WEEKLY,
19415 PeriodFreq::Daily,
19416 PeriodFreq::Business,
19417 PeriodFreq::Hourly,
19418 PeriodFreq::Minutely,
19419 PeriodFreq::Secondly,
19420 ];
19421 const SAMPLES: usize = 10;
19422
19423 let periods = (0..65_536)
19424 .map(|index| {
19425 let ordinal = if index % 4093 == 0 {
19426 i64::MIN
19427 } else {
19428 ((index as i64 * 7_919) % 4_000_001) - 2_000_000
19429 };
19430 Period::new(ordinal, FREQUENCIES[index % FREQUENCIES.len()])
19431 })
19432 .collect::<Vec<_>>();
19433
19434 for period in &periods {
19435 assert_eq!(period_display_former_profile(period), period.to_string());
19436 }
19437
19438 for _ in 0..2 {
19439 measure_period_renderer(&periods, period_display_former_profile);
19440 measure_period_renderer(&periods, Period::to_string);
19441 }
19442
19443 let mut former_ns = Vec::with_capacity(SAMPLES);
19444 let mut public_ns = Vec::with_capacity(SAMPLES);
19445 for sample in 0..SAMPLES {
19446 if sample % 2 == 0 {
19447 former_ns.push(measure_period_renderer(
19448 &periods,
19449 period_display_former_profile,
19450 ));
19451 public_ns.push(measure_period_renderer(&periods, Period::to_string));
19452 } else {
19453 public_ns.push(measure_period_renderer(&periods, Period::to_string));
19454 former_ns.push(measure_period_renderer(
19455 &periods,
19456 period_display_former_profile,
19457 ));
19458 }
19459 }
19460 former_ns.sort_unstable();
19461 public_ns.sort_unstable();
19462 let former_p50 = former_ns[SAMPLES / 2];
19463 let public_p50 = public_ns[SAMPLES / 2];
19464 let former_p95 = former_ns[SAMPLES - 1];
19465 let public_p95 = public_ns[SAMPLES - 1];
19466 println!("PROFILE_PERIOD_DISPLAY_FORMER_NS={former_ns:?}");
19467 println!("PROFILE_PERIOD_DISPLAY_PUBLIC_NS={public_ns:?}");
19468 println!(
19469 "PROFILE_PERIOD_DISPLAY_P50_RATIO={:.6}",
19470 former_p50 as f64 / public_p50 as f64
19471 );
19472 println!(
19473 "PROFILE_PERIOD_DISPLAY_P95_RATIO={:.6}",
19474 former_p95 as f64 / public_p95 as f64
19475 );
19476 }
19477
19478 #[cfg(test)]
19479 fn fp_days(ymd: &str) -> i64 {
19480 Period::parse(ymd).expect("daily period").ordinal
19481 }
19482
19483 #[test]
19484 fn period_roundtrips_through_serde_json() {
19485 let p = Period::new(42, PeriodFreq::WEEKLY);
19486 let json = serde_json::to_string(&p).expect("serialize");
19487 let back: Period = serde_json::from_str(&json).expect("deserialize");
19488 assert_eq!(p, back);
19489 }
19490
19491 use super::period_range;
19494
19495 #[test]
19496 fn period_range_zero_periods_is_empty() {
19497 let start = Period::new(216, PeriodFreq::QUARTERLY);
19498 assert!(period_range(start, 0).is_empty());
19499 }
19500
19501 #[test]
19502 fn period_range_single_period_returns_start_only() {
19503 let start = Period::new(216, PeriodFreq::QUARTERLY);
19504 let r = period_range(start, 1);
19505 assert_eq!(r.len(), 1);
19506 assert_eq!(r[0], start);
19507 }
19508
19509 #[test]
19510 fn period_range_increments_ordinal_by_one_per_step() {
19511 let start = Period::new(216, PeriodFreq::QUARTERLY);
19512 let r = period_range(start, 4);
19513 assert_eq!(r.len(), 4);
19514 assert_eq!(r[0].ordinal, 216);
19515 assert_eq!(r[1].ordinal, 217);
19516 assert_eq!(r[2].ordinal, 218);
19517 assert_eq!(r[3].ordinal, 219);
19518 }
19519
19520 #[test]
19521 fn period_range_preserves_frequency() {
19522 let start = Period::new(0, PeriodFreq::Monthly);
19523 let r = period_range(start, 12);
19524 assert!(r.iter().all(|p| p.freq == PeriodFreq::Monthly));
19525 }
19526
19527 #[test]
19528 fn period_range_negative_starting_ordinal_works() {
19529 let start = Period::new(-3, PeriodFreq::ANNUAL);
19531 let r = period_range(start, 5);
19532 assert_eq!(
19533 r.iter().map(|p| p.ordinal).collect::<Vec<_>>(),
19534 vec![-3, -2, -1, 0, 1]
19535 );
19536 }
19537
19538 #[test]
19539 fn period_range_large_n_does_not_panic() {
19540 let start = Period::new(0, PeriodFreq::Monthly);
19542 let r = period_range(start, 1024);
19543 assert_eq!(r.len(), 1024);
19544 assert_eq!(r[1023].ordinal, 1023);
19545 }
19546
19547 #[test]
19548 fn period_range_matches_seeded_ordinal_oracle_z3zh2() {
19549 fn next(seed: &mut u64) -> u64 {
19550 *seed = seed
19551 .wrapping_mul(6364136223846793005)
19552 .wrapping_add(1442695040888963407);
19553 *seed
19554 }
19555
19556 fn freq_for(raw: u64) -> PeriodFreq {
19557 match raw % 12 {
19560 0 => PeriodFreq::ANNUAL,
19561 1 => PeriodFreq::QUARTERLY,
19562 2 => PeriodFreq::Monthly,
19563 3 => PeriodFreq::WEEKLY,
19564 4 => PeriodFreq::Daily,
19565 5 => PeriodFreq::Business,
19566 6 => PeriodFreq::Hourly,
19567 7 => PeriodFreq::Minutely,
19568 8 => PeriodFreq::Secondly,
19569 9 => PeriodFreq::Milliseconds,
19570 10 => PeriodFreq::Microseconds,
19571 _ => PeriodFreq::Nanoseconds,
19572 }
19573 }
19574
19575 fn assert_oracle_case(case: usize, start: Period, periods: usize) {
19576 let got = period_range(start, periods);
19577 assert_eq!(got.len(), periods, "case {case}: length");
19578
19579 for (position, period) in got.iter().enumerate() {
19580 let expected_ordinal = start.ordinal.saturating_add(position as i64);
19581 assert_eq!(
19582 period.ordinal, expected_ordinal,
19583 "case {case}: ordinal at {position}"
19584 );
19585 assert_eq!(period.freq, start.freq, "case {case}: freq at {position}");
19586 }
19587 }
19588
19589 assert_oracle_case(usize::MAX, Period::new(42, PeriodFreq::Monthly), 0);
19590 assert_oracle_case(
19591 usize::MAX - 1,
19592 Period::new(i64::MAX - 3, PeriodFreq::Daily),
19593 8,
19594 );
19595
19596 let mut seed = 0x9e21_0d1c_5eed_0421_u64;
19597 for case in 0..260 {
19598 let freq = freq_for(next(&mut seed));
19599 let periods = (next(&mut seed) % 80) as usize;
19600 let start_ordinal = if case % 37 == 0 {
19601 i64::MAX - 7
19602 } else {
19603 (next(&mut seed) % 20_001) as i64 - 10_000
19604 };
19605 assert_oracle_case(case, Period::new(start_ordinal, freq), periods);
19606 }
19607 }
19608
19609 use super::{TypeError, interval_range, interval_range_by_periods, interval_range_by_step};
19612
19613 #[test]
19614 fn interval_range_by_periods_matches_pandas_default_case() {
19615 let bins = interval_range_by_periods(0.0, 10.0, 5, IntervalClosed::Right);
19617 assert_eq!(bins.len(), 5);
19618 for (i, bin) in bins.iter().enumerate() {
19619 assert_eq!(bin.left, (i as f64) * 2.0);
19620 assert_eq!(bin.right, ((i + 1) as f64) * 2.0);
19621 assert_eq!(bin.closed, IntervalClosed::Right);
19622 }
19623 }
19624
19625 #[test]
19626 fn interval_range_by_periods_final_edge_is_exact_end() {
19627 let bins = interval_range_by_periods(0.0, 1.0, 7, IntervalClosed::Right);
19629 assert_eq!(bins.last().unwrap().right, 1.0);
19630 }
19631
19632 #[test]
19633 fn interval_range_by_periods_zero_periods_is_empty() {
19634 assert!(interval_range_by_periods(0.0, 10.0, 0, IntervalClosed::Right).is_empty());
19635 }
19636
19637 #[test]
19638 fn interval_range_by_periods_reversed_range_is_empty() {
19639 assert!(interval_range_by_periods(10.0, 0.0, 5, IntervalClosed::Right).is_empty());
19641 }
19642
19643 #[test]
19644 fn interval_range_by_periods_preserves_closed_policy() {
19645 for closed in [
19646 IntervalClosed::Left,
19647 IntervalClosed::Right,
19648 IntervalClosed::Both,
19649 IntervalClosed::Neither,
19650 ] {
19651 let bins = interval_range_by_periods(0.0, 4.0, 2, closed);
19652 assert!(bins.iter().all(|b| b.closed == closed));
19653 }
19654 }
19655
19656 #[test]
19657 fn interval_range_by_step_matches_pandas_default_case() {
19658 let bins = interval_range_by_step(0.0, 10.0, 2.0, IntervalClosed::Right).expect("ok");
19660 assert_eq!(bins.len(), 5);
19661 assert_eq!(bins[0].left, 0.0);
19662 assert_eq!(bins[4].right, 10.0);
19663 }
19664
19665 #[test]
19666 fn interval_range_by_step_rejects_non_positive_step() {
19667 assert!(matches!(
19668 interval_range_by_step(0.0, 10.0, 0.0, IntervalClosed::Right),
19669 Err(TypeError::InvalidIntervalStep { .. })
19670 ));
19671 assert!(matches!(
19672 interval_range_by_step(0.0, 10.0, -2.0, IntervalClosed::Right),
19673 Err(TypeError::InvalidIntervalStep { .. })
19674 ));
19675 assert!(matches!(
19676 interval_range_by_step(0.0, 10.0, f64::NAN, IntervalClosed::Right),
19677 Err(TypeError::InvalidIntervalStep { .. })
19678 ));
19679 assert!(matches!(
19680 interval_range_by_step(0.0, 10.0, f64::INFINITY, IntervalClosed::Right),
19681 Err(TypeError::InvalidIntervalStep { .. })
19682 ));
19683 }
19684
19685 #[test]
19686 fn interval_range_by_step_rejects_non_dividing_step() {
19687 assert!(matches!(
19690 interval_range_by_step(0.0, 10.0, 3.0, IntervalClosed::Right),
19691 Err(TypeError::IntervalStepDoesNotDivide { .. })
19692 ));
19693 }
19694
19695 #[test]
19696 fn interval_range_by_step_reversed_range_is_empty() {
19697 let bins = interval_range_by_step(10.0, 0.0, 2.0, IntervalClosed::Right).expect("ok");
19698 assert!(bins.is_empty());
19699 }
19700
19701 #[test]
19702 fn interval_range_by_step_degenerate_zero_span_is_empty() {
19703 let bins = interval_range_by_step(5.0, 5.0, 1.0, IntervalClosed::Right).expect("ok");
19704 assert!(bins.is_empty());
19705 }
19706
19707 #[test]
19708 fn interval_range_by_step_accepts_float_step_within_tolerance() {
19709 let bins = interval_range_by_step(0.0, 1.0, 0.1, IntervalClosed::Right).expect("ok");
19711 assert_eq!(bins.len(), 10);
19712 assert_eq!(bins.last().unwrap().right, 1.0);
19713 }
19714
19715 #[test]
19716 fn interval_range_unified_api_tests() {
19717 let r1 = interval_range(Some(0.0), Some(10.0), Some(5), None, None).expect("ok");
19719 assert_eq!(r1.len(), 5);
19720 assert_eq!(r1[0].left, 0.0);
19721 assert_eq!(r1[0].right, 2.0);
19722 assert_eq!(r1[4].right, 10.0);
19723 assert_eq!(r1[0].closed, IntervalClosed::Right);
19724
19725 let r2 = interval_range(Some(0.0), Some(10.0), None, Some(2.0), None).expect("ok");
19727 assert_eq!(r2.len(), 5);
19728 assert_eq!(r2[0].left, 0.0);
19729 assert_eq!(r2[4].right, 10.0);
19730
19731 let r3 = interval_range(
19733 Some(0.0),
19734 None,
19735 Some(5),
19736 Some(2.0),
19737 Some(IntervalClosed::Both),
19738 )
19739 .expect("ok");
19740 assert_eq!(r3.len(), 5);
19741 assert_eq!(r3[0].left, 0.0);
19742 assert_eq!(r3[4].right, 10.0);
19743 assert_eq!(r3[0].closed, IntervalClosed::Both);
19744
19745 let r4 = interval_range(
19747 None,
19748 Some(10.0),
19749 Some(5),
19750 Some(2.0),
19751 Some(IntervalClosed::Left),
19752 )
19753 .expect("ok");
19754 assert_eq!(r4.len(), 5);
19755 assert_eq!(r4[0].left, 0.0);
19756 assert_eq!(r4[4].right, 10.0);
19757 assert_eq!(r4[0].closed, IntervalClosed::Left);
19758
19759 assert!(matches!(
19761 interval_range(None, None, None, None, None),
19762 Err(TypeError::IntervalRangeParameterCount)
19763 ));
19764 assert!(matches!(
19765 interval_range(Some(0.0), Some(10.0), None, None, None),
19766 Err(TypeError::IntervalRangeParameterCount)
19767 ));
19768 assert!(matches!(
19769 interval_range(Some(0.0), Some(10.0), Some(5), Some(2.0), None),
19770 Err(TypeError::IntervalRangeParameterCount)
19771 ));
19772
19773 assert!(matches!(
19775 interval_range(Some(0.0), None, Some(5), Some(-1.0), None),
19776 Err(TypeError::InvalidIntervalStep { .. })
19777 ));
19778 assert!(matches!(
19779 interval_range(Some(0.0), None, Some(5), Some(0.0), None),
19780 Err(TypeError::InvalidIntervalStep { .. })
19781 ));
19782 }
19783
19784 #[test]
19785 fn interval_range_matches_seeded_arithmetic_oracle_t9ozf() {
19786 fn next(seed: &mut u64) -> u64 {
19789 *seed = seed
19790 .wrapping_mul(2862933555777941757)
19791 .wrapping_add(3037000493);
19792 *seed
19793 }
19794
19795 fn closed_for(raw: u64) -> IntervalClosed {
19796 match raw % 4 {
19797 0 => IntervalClosed::Left,
19798 1 => IntervalClosed::Right,
19799 2 => IntervalClosed::Both,
19800 _ => IntervalClosed::Neither,
19801 }
19802 }
19803
19804 fn assert_interval(
19805 case: usize,
19806 kind: &str,
19807 pos: usize,
19808 actual: &Interval,
19809 expected: &Interval,
19810 ) {
19811 assert!(
19812 (actual.left - expected.left).abs() < 1e-12,
19813 "case={case} kind={kind} pos={pos}: expected left {}, got {}",
19814 expected.left,
19815 actual.left
19816 );
19817 assert!(
19818 (actual.right - expected.right).abs() < 1e-12,
19819 "case={case} kind={kind} pos={pos}: expected right {}, got {}",
19820 expected.right,
19821 actual.right
19822 );
19823 assert_eq!(
19824 actual.closed, expected.closed,
19825 "case={case} kind={kind} pos={pos}: closed mismatch"
19826 );
19827 }
19828
19829 fn expected_by_periods(
19830 start: f64,
19831 end: f64,
19832 periods: usize,
19833 closed: IntervalClosed,
19834 ) -> Vec<Interval> {
19835 if periods == 0 || !start.is_finite() || !end.is_finite() || start >= end {
19836 return Vec::new();
19837 }
19838 let step = (end - start) / periods as f64;
19839 (0..periods)
19840 .map(|pos| {
19841 let left = start + step * pos as f64;
19842 let right = if pos + 1 == periods {
19843 end
19844 } else {
19845 start + step * (pos + 1) as f64
19846 };
19847 Interval::new(left, right, closed)
19848 })
19849 .collect()
19850 }
19851
19852 fn expected_by_step(
19853 start: f64,
19854 end: f64,
19855 step: f64,
19856 closed: IntervalClosed,
19857 ) -> Vec<Interval> {
19858 if start >= end {
19859 return Vec::new();
19860 }
19861 let count = ((end - start) / step).round() as usize;
19862 (0..count)
19863 .map(|pos| {
19864 let left = start + step * pos as f64;
19865 let right = if pos + 1 == count {
19866 end
19867 } else {
19868 start + step * (pos + 1) as f64
19869 };
19870 Interval::new(left, right, closed)
19871 })
19872 .collect()
19873 }
19874
19875 assert!(interval_range_by_periods(5.0, 5.0, 4, IntervalClosed::Right).is_empty());
19876 assert!(interval_range_by_periods(5.0, 4.0, 4, IntervalClosed::Right).is_empty());
19877 assert!(
19878 interval_range_by_step(5.0, 5.0, 1.0, IntervalClosed::Right)
19879 .expect("zero span")
19880 .is_empty()
19881 );
19882
19883 let mut seed = 0x171e_7a11_c0de_5eed_u64;
19884 for case in 0..220 {
19885 let start = (next(&mut seed) % 2_001) as f64 / 10.0 - 100.0;
19886 let periods = (next(&mut seed) % 24 + 1) as usize;
19887 let width = (next(&mut seed) % 1_000 + 1) as f64 / 4.0;
19888 let end = start + width;
19889 let closed = closed_for(next(&mut seed));
19890
19891 let actual = interval_range_by_periods(start, end, periods, closed);
19892 let expected = expected_by_periods(start, end, periods, closed);
19893 assert_eq!(
19894 actual.len(),
19895 expected.len(),
19896 "case={case} periods: length mismatch"
19897 );
19898 for (pos, (actual, expected)) in actual.iter().zip(expected.iter()).enumerate() {
19899 assert_interval(case, "periods", pos, actual, expected);
19900 }
19901
19902 let step_count = (next(&mut seed) % 20 + 1) as usize;
19903 let step = (next(&mut seed) % 25 + 1) as f64;
19904 let step_end = start + step * step_count as f64;
19905 let actual = interval_range_by_step(start, step_end, step, closed).expect("divides");
19906 let expected = expected_by_step(start, step_end, step, closed);
19907 assert_eq!(
19908 actual.len(),
19909 expected.len(),
19910 "case={case} step: length mismatch"
19911 );
19912 for (pos, (actual, expected)) in actual.iter().zip(expected.iter()).enumerate() {
19913 assert_interval(case, "step", pos, actual, expected);
19914 }
19915 }
19916 }
19917
19918 use super::Timedelta;
19921
19922 #[test]
19923 fn timedelta_add_sums_non_nat() {
19924 let one_hour = Timedelta::NANOS_PER_HOUR;
19925 let one_day = Timedelta::NANOS_PER_DAY;
19926 assert_eq!(Timedelta::add(one_hour, one_day), one_hour + one_day);
19927 }
19928
19929 #[test]
19930 fn timedelta_add_propagates_nat() {
19931 assert_eq!(Timedelta::add(Timedelta::NAT, 100), Timedelta::NAT);
19932 assert_eq!(Timedelta::add(100, Timedelta::NAT), Timedelta::NAT);
19933 assert_eq!(
19934 Timedelta::add(Timedelta::NAT, Timedelta::NAT),
19935 Timedelta::NAT
19936 );
19937 }
19938
19939 #[test]
19940 fn timedelta_add_returns_nat_on_overflow() {
19941 assert_eq!(Timedelta::add(i64::MAX - 10, 100), Timedelta::NAT);
19948 assert_eq!(Timedelta::add(i64::MIN + 10, -100), Timedelta::NAT);
19951 }
19952
19953 #[test]
19954 fn timedelta_sub_subtracts_non_nat() {
19955 let one_hour = Timedelta::NANOS_PER_HOUR;
19956 assert_eq!(
19957 Timedelta::sub(one_hour, Timedelta::NANOS_PER_MIN),
19958 one_hour - Timedelta::NANOS_PER_MIN
19959 );
19960 }
19961
19962 #[test]
19963 fn timedelta_sub_propagates_nat() {
19964 assert_eq!(Timedelta::sub(Timedelta::NAT, 100), Timedelta::NAT);
19965 assert_eq!(Timedelta::sub(100, Timedelta::NAT), Timedelta::NAT);
19966 }
19967
19968 #[test]
19969 fn timedelta_neg_flips_sign_non_nat() {
19970 assert_eq!(Timedelta::neg(5), -5);
19971 assert_eq!(Timedelta::neg(-5), 5);
19972 assert_eq!(Timedelta::neg(0), 0);
19973 }
19974
19975 #[test]
19976 fn timedelta_neg_preserves_nat() {
19977 assert_eq!(Timedelta::neg(Timedelta::NAT), Timedelta::NAT);
19978 }
19979
19980 #[test]
19981 fn timedelta_abs_returns_magnitude() {
19982 assert_eq!(Timedelta::abs(-5), 5);
19983 assert_eq!(Timedelta::abs(5), 5);
19984 assert_eq!(Timedelta::abs(0), 0);
19985 assert_eq!(Timedelta::abs(Timedelta::NAT), Timedelta::NAT);
19986 }
19987
19988 #[test]
19989 fn neg_and_abs_at_the_representable_floor_are_not_overflow_fyr1z() {
19990 const MAX: i64 = i64::MAX;
20008 const MIN_OK: i64 = i64::MIN + 1; assert_eq!(MIN_OK, -MAX);
20013 assert_eq!(Timedelta::NAT, i64::MIN);
20014
20015 assert_eq!(Timedelta::neg(MIN_OK), MAX);
20017 assert_eq!(Timedelta::neg(MAX), MIN_OK);
20018 assert_eq!(Timedelta::abs(MIN_OK), MAX);
20019 assert_eq!(Timedelta::abs(MAX), MAX);
20020
20021 assert_eq!(Timedelta::neg(Timedelta::neg(MIN_OK)), MIN_OK);
20025 assert_ne!(Timedelta::neg(MIN_OK), Timedelta::NAT);
20026 assert_ne!(Timedelta::abs(MIN_OK), Timedelta::NAT);
20027
20028 assert_eq!(Timedelta::neg(Timedelta::NAT), Timedelta::NAT);
20031 assert_eq!(Timedelta::abs(Timedelta::NAT), Timedelta::NAT);
20032 }
20033
20034 #[test]
20035 fn overflow_divergence_surface_is_only_where_pandas_refuses_fyr1z() {
20036 const MAX: i64 = i64::MAX;
20048 const MIN_OK: i64 = i64::MIN + 1;
20049
20050 assert_eq!(Timedelta::div_scalar(MAX, 0), Timedelta::NAT);
20055 assert_eq!(Timedelta::div_scalar(MIN_OK, 0), Timedelta::NAT);
20056 assert_eq!(Timedelta::div_scalar(0, 0), Timedelta::NAT);
20057
20058 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());
20068 assert!(Timestamp::from_nanos(MIN_OK).sub_timedelta(2).is_nat());
20069
20070 assert_eq!(Timedelta::add(MAX, 1), Timedelta::NAT);
20074 assert_eq!(Timedelta::mul_scalar(MAX, 2), Timedelta::NAT);
20075 assert!(Timestamp::from_nanos(MAX).add_timedelta(1).is_nat());
20076
20077 assert_eq!(Timedelta::div_scalar(MAX, 1), MAX);
20079 assert_eq!(Timedelta::div_scalar(-100, 3), -34); assert_eq!(Timedelta::div_scalar(100, -3), -34);
20081 assert_eq!(Timedelta::sub(MIN_OK + 2, 1), MIN_OK + 1);
20082 }
20083
20084 #[test]
20085 fn timedelta_mul_scalar_scales() {
20086 let three_hours = Timedelta::NANOS_PER_HOUR * 3;
20087 assert_eq!(
20088 Timedelta::mul_scalar(Timedelta::NANOS_PER_HOUR, 3),
20089 three_hours
20090 );
20091 assert_eq!(Timedelta::mul_scalar(100, 0), 0);
20092 assert_eq!(Timedelta::mul_scalar(100, -2), -200);
20093 }
20094
20095 #[test]
20096 fn timedelta_mul_scalar_returns_nat_on_overflow() {
20097 assert_eq!(Timedelta::mul_scalar(i64::MAX, 2), Timedelta::NAT);
20100 assert_eq!(Timedelta::mul_scalar(i64::MIN + 1, 2), Timedelta::NAT);
20101 }
20102
20103 #[test]
20104 fn from_unit_nan_is_nat_and_overflow_is_err_8v92m() {
20105 use super::TimedeltaError;
20106
20107 assert_eq!(Timedelta::from_unit(f64::NAN, "s"), Ok(Timedelta::NAT));
20125 assert_ne!(Timedelta::from_unit(f64::NAN, "s"), Ok(0));
20126 assert_eq!(Timedelta::from_unit(f64::NAN, "D"), Ok(Timedelta::NAT));
20127
20128 assert_eq!(
20130 Timedelta::from_unit(f64::INFINITY, "s"),
20131 Err(TimedeltaError::Overflow)
20132 );
20133 assert_eq!(
20134 Timedelta::from_unit(f64::NEG_INFINITY, "s"),
20135 Err(TimedeltaError::Overflow)
20136 );
20137 assert_eq!(
20138 Timedelta::from_unit(1e30, "s"),
20139 Err(TimedeltaError::Overflow)
20140 );
20141 assert_eq!(
20142 Timedelta::from_unit(1e30, "D"),
20143 Err(TimedeltaError::Overflow)
20144 );
20145
20146 assert_eq!(Timedelta::from_unit(1.5, "s"), Ok(1_500_000_000));
20149 assert_eq!(Timedelta::from_unit(0.0, "s"), Ok(0));
20150 assert_eq!(Timedelta::from_unit(-2.5, "s"), Ok(-2_500_000_000));
20151 assert_eq!(Timedelta::from_unit(1.0, "D"), Ok(Timedelta::NANOS_PER_DAY));
20152 assert_eq!(
20153 Timedelta::from_unit(3.0, "h"),
20154 Ok(3 * Timedelta::NANOS_PER_HOUR)
20155 );
20156 let big_days = 100_000.0_f64;
20159 let expected = (big_days * Timedelta::NANOS_PER_DAY as f64).round() as i64;
20160 assert_eq!(Timedelta::from_unit(big_days, "D"), Ok(expected));
20161 assert!(expected > 0, "fixture must stay in range to be a control");
20162
20163 assert!(matches!(
20166 Timedelta::from_unit(1.0, "nonsense-unit"),
20167 Err(TimedeltaError::InvalidFormat(_))
20168 ));
20169 assert!(matches!(
20170 Timedelta::from_unit(f64::NAN, "nonsense-unit"),
20171 Err(TimedeltaError::InvalidFormat(_)),
20172 ));
20173
20174 let huge = format!("{} days", "9".repeat(18));
20179 assert!(matches!(
20180 Timedelta::parse(&huge),
20181 Err(TimedeltaError::Overflow)
20182 ));
20183 assert!(matches!(
20184 Timedelta::parse("1e100 days"),
20185 Err(TimedeltaError::InvalidFormat(_))
20186 ));
20187 }
20188
20189 #[test]
20190 fn rounding_and_ms_us_overflow_never_fabricates_a_finite_value_kyd16() {
20191 const MAX: i64 = i64::MAX;
20210 const MIN_OK: i64 = i64::MIN + 1;
20211 const DAY: i64 = Timedelta::NANOS_PER_DAY;
20212
20213 let rounded = Timedelta::round(MAX, "D");
20215 assert_eq!(
20216 rounded,
20217 Timedelta::NAT,
20218 "rounding i64::MAX up to a whole day overflows; the old unchecked \
20219 multiply panicked in debug and wrapped in release"
20220 );
20221 assert!(
20225 rounded == Timedelta::NAT || rounded > 0,
20226 "a positive duration must never round to a negative one"
20227 );
20228 assert_eq!(Timedelta::round(MIN_OK, "D"), Timedelta::NAT);
20229
20230 assert_eq!(Timedelta::ceil(MAX, "D"), Timedelta::NAT);
20232 assert_eq!(Timedelta::floor(MIN_OK, "D"), Timedelta::NAT);
20233 assert!(Timestamp::from_nanos(MAX).ceil_to(DAY).is_nat());
20234 assert!(Timestamp::from_nanos(MAX).round_to(DAY).is_nat());
20235 assert!(Timestamp::from_nanos(MIN_OK).floor_to(DAY).is_nat());
20236 assert!(Timestamp::from_nanos(MIN_OK).round_to(DAY).is_nat());
20237
20238 assert!(Timestamp::from_millis(MAX, None).is_nat());
20240 assert!(Timestamp::from_millis(MIN_OK, None).is_nat());
20241 assert!(Timestamp::from_micros(MAX, None).is_nat());
20242 assert!(Timestamp::from_micros(MIN_OK, Some("US/Eastern")).is_nat());
20243
20244 let max_floor = Timestamp::from_nanos(MAX).floor_to(DAY);
20251 assert!(!max_floor.is_nat(), "Timestamp.max.floor(D) must succeed");
20252 assert_eq!(max_floor.nanos, (MAX / DAY) * DAY);
20253 assert_eq!(Timedelta::floor(MAX, "D"), (MAX / DAY) * DAY);
20254 assert_eq!(
20255 Timedelta::ceil(MIN_OK, "D"),
20256 (MIN_OK.div_euclid(DAY) + 1) * DAY
20257 );
20258
20259 let hour = Timedelta::NANOS_PER_HOUR;
20261 assert_eq!(Timedelta::floor(90 * 60 * 1_000_000_000, "h"), hour);
20262 assert_eq!(Timedelta::ceil(90 * 60 * 1_000_000_000, "h"), 2 * hour);
20263 assert_eq!(Timedelta::round(90 * 60 * 1_000_000_000, "h"), 2 * hour);
20264 assert_eq!(Timedelta::round(-90 * 60 * 1_000_000_000, "h"), -2 * hour);
20265 assert_eq!(Timedelta::round(29 * 60 * 1_000_000_000, "h"), 0);
20266 assert_eq!(Timestamp::from_millis(1_500, None).nanos, 1_500_000_000);
20267 assert_eq!(Timestamp::from_micros(-2_000, None).nanos, -2_000_000);
20268 assert_eq!(
20269 Timestamp::from_nanos(hour + 1).floor_to(hour).nanos,
20270 hour,
20271 "in-range floor unchanged"
20272 );
20273 assert_eq!(
20274 Timestamp::from_nanos(hour + 1).ceil_to(hour).nanos,
20275 2 * hour,
20276 "in-range ceil unchanged"
20277 );
20278
20279 assert_eq!(Timedelta::round(Timedelta::NAT, "D"), Timedelta::NAT);
20281 assert_eq!(Timedelta::floor(Timedelta::NAT, "D"), Timedelta::NAT);
20282 assert_eq!(Timedelta::ceil(1_000, "nonsense-unit"), Timedelta::NAT);
20283 assert!(Timestamp::nat().ceil_to(DAY).is_nat());
20284 assert!(Timestamp::from_nanos(0).round_to(0).is_nat());
20285 assert_eq!(
20287 Timestamp::from_nanos_tz(hour + 1, "US/Eastern")
20288 .ceil_to(hour)
20289 .tz
20290 .as_deref(),
20291 Some("US/Eastern")
20292 );
20293 }
20294
20295 #[test]
20296 fn timedelta_mul_scalar_propagates_nat() {
20297 assert_eq!(Timedelta::mul_scalar(Timedelta::NAT, 5), Timedelta::NAT);
20298 }
20299
20300 #[test]
20301 fn arithmetic_overflow_never_fabricates_a_finite_value_lgyy8() {
20302 const MAX: i64 = i64::MAX;
20317 const MIN_OK: i64 = i64::MIN + 1; assert_eq!(Timedelta::add(MAX, 1), Timedelta::NAT);
20321 assert_eq!(Timedelta::add(MAX - 10, 100), Timedelta::NAT);
20322 assert_eq!(Timedelta::sub(MAX, -1), Timedelta::NAT);
20323 assert_eq!(Timedelta::mul_scalar(MAX, 2), Timedelta::NAT);
20324 assert_eq!(Timedelta::mul_scalar(MAX / 2 + 2, 2), Timedelta::NAT);
20325 assert!(Timestamp::from_nanos(MAX).add_timedelta(1).is_nat());
20326 assert!(Timestamp::from_nanos(MAX).sub_timedelta(-1).is_nat());
20327 assert_eq!(
20331 Timestamp::from_nanos(MAX).sub_timestamp(&Timestamp::from_nanos(MIN_OK)),
20332 Timedelta::NAT
20333 );
20334
20335 assert_eq!(Timedelta::add(MIN_OK, -1), Timedelta::NAT);
20337 assert_eq!(Timedelta::add(MIN_OK, -2), Timedelta::NAT);
20338 assert_eq!(Timedelta::sub(MIN_OK, 1), Timedelta::NAT);
20339 assert_eq!(Timedelta::mul_scalar(MIN_OK, 2), Timedelta::NAT);
20340 assert!(Timestamp::from_nanos(MIN_OK).sub_timedelta(1).is_nat());
20341 assert!(Timestamp::from_nanos(MIN_OK).add_timedelta(-1).is_nat());
20342 assert_eq!(
20343 Timestamp::from_nanos(MIN_OK).sub_timestamp(&Timestamp::from_nanos(MAX)),
20344 Timedelta::NAT
20345 );
20346
20347 assert_eq!(Timedelta::add(MAX - 1, 1), MAX);
20353 assert_eq!(Timedelta::add(MAX, 0), MAX);
20354 assert_eq!(Timedelta::sub(MAX, 1), MAX - 1);
20355 assert_eq!(Timedelta::add(MIN_OK + 1, -1), MIN_OK);
20356 assert_eq!(Timedelta::mul_scalar(MAX / 2, 2), (MAX / 2) * 2);
20357 assert_eq!(Timedelta::mul_scalar(MIN_OK, 1), MIN_OK);
20358 assert_eq!(Timestamp::from_nanos(MAX - 1).add_timedelta(1).nanos, MAX);
20359 assert_eq!(
20360 Timestamp::from_nanos(MIN_OK + 1).sub_timedelta(1).nanos,
20361 MIN_OK
20362 );
20363 assert_eq!(
20364 Timestamp::from_nanos(MAX).sub_timestamp(&Timestamp::from_nanos(0)),
20365 MAX
20366 );
20367 assert_eq!(Timedelta::add(1_000, 2_345), 3_345);
20369 assert_eq!(Timedelta::sub(1_000, 2_345), -1_345);
20370 assert_eq!(Timedelta::mul_scalar(-7, 6), -42);
20371
20372 assert_eq!(MIN_OK - 1, i64::MIN);
20379 assert_eq!(Timedelta::sub(MIN_OK, 1), Timedelta::NAT);
20380 assert_eq!(Timedelta::add(MIN_OK, 0), MIN_OK);
20381
20382 assert!(Timestamp::nat().add_timedelta(1).is_nat());
20385 assert!(
20386 Timestamp::from_nanos(0)
20387 .add_timedelta(Timedelta::NAT)
20388 .is_nat()
20389 );
20390 let tzed = Timestamp::from_nanos_tz(MAX, "US/Eastern");
20391 let overflowed = tzed.add_timedelta(1);
20392 assert!(overflowed.is_nat());
20393 assert_eq!(overflowed.tz, None, "an overflow NaT carries no zone");
20394 assert_eq!(
20396 Timestamp::from_nanos_tz(0, "US/Eastern")
20397 .add_timedelta(Timedelta::NANOS_PER_DAY)
20398 .tz
20399 .as_deref(),
20400 Some("US/Eastern")
20401 );
20402 }
20403
20404 #[test]
20405 fn timedelta_div_scalar_floor_divides() {
20406 assert_eq!(Timedelta::div_scalar(100, 3), 33);
20408 assert_eq!(Timedelta::div_scalar(-100, 3), -34);
20409 assert_eq!(Timedelta::div_scalar(100, -3), -34);
20410 assert_eq!(Timedelta::div_scalar(-100, -3), 33);
20411 }
20412
20413 #[test]
20414 fn timedelta_div_scalar_zero_divisor_returns_nat() {
20415 assert_eq!(Timedelta::div_scalar(100, 0), Timedelta::NAT);
20416 }
20417
20418 #[test]
20419 fn timedelta_div_scalar_min_neg_one_propagates_nat() {
20420 assert_eq!(Timedelta::div_scalar(i64::MIN, -1), Timedelta::NAT);
20423 assert_eq!(Timedelta::div_scalar(i64::MIN + 1, -1), i64::MAX);
20425 }
20426
20427 #[test]
20428 fn timedelta_div_scalar_propagates_nat() {
20429 assert_eq!(Timedelta::div_scalar(Timedelta::NAT, 10), Timedelta::NAT);
20430 }
20431
20432 #[test]
20433 fn timedelta_div_timedelta_returns_float_ratio() {
20434 let two_hours = Timedelta::NANOS_PER_HOUR * 2;
20435 let one_hour = Timedelta::NANOS_PER_HOUR;
20436 assert!((Timedelta::div_timedelta(two_hours, one_hour) - 2.0).abs() < 1e-12);
20437 assert!((Timedelta::div_timedelta(one_hour, two_hours) - 0.5).abs() < 1e-12);
20438 }
20439
20440 #[test]
20441 fn timedelta_div_timedelta_nat_returns_nan() {
20442 assert!(Timedelta::div_timedelta(Timedelta::NAT, 100).is_nan());
20443 assert!(Timedelta::div_timedelta(100, Timedelta::NAT).is_nan());
20444 }
20445
20446 use super::Timestamp;
20449
20450 #[test]
20451 fn timestamp_from_nanos_is_naive_utc() {
20452 let ts = Timestamp::from_nanos(1_700_000_000_000_000_000);
20453 assert_eq!(ts.nanos, 1_700_000_000_000_000_000);
20454 assert_eq!(ts.tz, None);
20455 assert!(!ts.is_nat());
20456 }
20457
20458 #[test]
20459 fn timestamp_from_nanos_tz_carries_tz_name() {
20460 let ts = Timestamp::from_nanos_tz(1_700_000_000_000_000_000, "US/Eastern");
20461 assert_eq!(ts.tz.as_deref(), Some("US/Eastern"));
20462 }
20463
20464 #[test]
20465 fn timestamp_now_returns_current_time() {
20466 let before = std::time::SystemTime::now()
20467 .duration_since(std::time::UNIX_EPOCH)
20468 .unwrap()
20469 .as_nanos() as i64;
20470 let ts = Timestamp::now();
20471 let after = std::time::SystemTime::now()
20472 .duration_since(std::time::UNIX_EPOCH)
20473 .unwrap()
20474 .as_nanos() as i64;
20475 assert!(ts.nanos >= before);
20476 assert!(ts.nanos <= after);
20477 assert!(!ts.is_nat());
20478 }
20479
20480 #[test]
20481 fn timestamp_today_returns_midnight() {
20482 let ts = Timestamp::today();
20483 assert!(!ts.is_nat());
20484 assert_eq!(ts.hour(), Some(0));
20486 assert_eq!(ts.minute(), Some(0));
20487 assert_eq!(ts.second(), Some(0));
20488 }
20489
20490 #[test]
20491 fn timestamp_add_timedelta_shifts_nanos_and_preserves_tz() {
20492 let ts = Timestamp::from_nanos_tz(0, "US/Eastern");
20493 let one_day = Timedelta::NANOS_PER_DAY;
20494 let shifted = ts.add_timedelta(one_day);
20495 assert_eq!(shifted.nanos, one_day);
20496 assert_eq!(shifted.tz.as_deref(), Some("US/Eastern"));
20497 }
20498
20499 #[test]
20500 fn timestamp_add_timedelta_returns_nat_on_overflow() {
20501 let ts = Timestamp::from_nanos(i64::MAX - 10);
20505 assert!(ts.add_timedelta(100).is_nat());
20506 }
20507
20508 #[test]
20509 fn timestamp_add_timedelta_propagates_nat() {
20510 assert!(Timestamp::nat().add_timedelta(100).is_nat());
20512 assert!(
20514 Timestamp::from_nanos(0)
20515 .add_timedelta(Timedelta::NAT)
20516 .is_nat()
20517 );
20518 }
20519
20520 #[test]
20521 fn timestamp_sub_timedelta_shifts_backward() {
20522 let ts = Timestamp::from_nanos(1_000);
20523 let shifted = ts.sub_timedelta(Timedelta::NANOS_PER_MICRO);
20524 assert_eq!(shifted.nanos, 0);
20525 }
20526
20527 #[test]
20528 fn timestamp_sub_timestamp_returns_timedelta_nanos() {
20529 let t0 = Timestamp::from_nanos(0);
20530 let t1 = Timestamp::from_nanos(Timedelta::NANOS_PER_HOUR);
20531 assert_eq!(t1.sub_timestamp(&t0), Timedelta::NANOS_PER_HOUR);
20532 assert_eq!(t0.sub_timestamp(&t1), -Timedelta::NANOS_PER_HOUR);
20533 }
20534
20535 #[test]
20536 fn timestamp_sub_timestamp_nat_propagates() {
20537 let ts = Timestamp::from_nanos(1_000);
20538 assert_eq!(Timestamp::nat().sub_timestamp(&ts), Timedelta::NAT);
20539 assert_eq!(ts.sub_timestamp(&Timestamp::nat()), Timedelta::NAT);
20540 }
20541
20542 #[test]
20543 fn timestamp_semantic_eq_treats_two_nat_as_equal() {
20544 assert!(Timestamp::nat().semantic_eq(&Timestamp::nat()));
20545 assert!(!Timestamp::nat().semantic_eq(&Timestamp::from_nanos(0)));
20546 assert!(!Timestamp::from_nanos(0).semantic_eq(&Timestamp::nat()));
20547 }
20548
20549 #[test]
20550 fn timestamp_partial_cmp_orders_by_nanos_nat_is_incomparable() {
20551 use std::cmp::Ordering;
20552 let a = Timestamp::from_nanos(0);
20553 let b = Timestamp::from_nanos(100);
20554 assert_eq!(a.partial_cmp(&b), Some(Ordering::Less));
20555 assert_eq!(b.partial_cmp(&a), Some(Ordering::Greater));
20556 assert_eq!(a.partial_cmp(&a), Some(Ordering::Equal));
20557 assert_eq!(a.partial_cmp(&Timestamp::nat()), None);
20558 assert_eq!(Timestamp::nat().partial_cmp(&Timestamp::nat()), None);
20559 }
20560
20561 #[test]
20562 fn time_zone_offsets_and_wall_clock_conversions_follow_pandas() {
20563 use crate::{
20564 TimeZoneError, tz_abbreviation, tz_canonical_name, tz_offset_seconds,
20565 tz_utc_to_wall_nanos, tz_validate, tz_wall_to_utc_nanos,
20566 };
20567 let hour = 3_600_000_000_000_i64;
20568 let instant = 1_710_081_000_000_000_000_i64;
20571 assert_eq!(tz_offset_seconds("Asia/Tokyo", instant), Ok(9 * 3_600));
20572 assert_eq!(tz_offset_seconds("US/Eastern", instant), Ok(-4 * 3_600));
20573 assert_eq!(
20574 tz_offset_seconds("US/Eastern", instant - 24 * hour),
20575 Ok(-5 * 3_600)
20576 );
20577 assert_eq!(tz_offset_seconds("+05:30", 0), Ok(19_800));
20578 assert_eq!(tz_offset_seconds("UTC+05:30", 0), Ok(19_800));
20579 assert_eq!(tz_offset_seconds("-03:00", 0), Ok(-10_800));
20580 assert_eq!(tz_offset_seconds("UTC", instant), Ok(0));
20581 assert_eq!(
20582 tz_utc_to_wall_nanos("Asia/Tokyo", instant),
20583 Ok(instant + 9 * hour)
20584 );
20585 let wall_noon = 19_723 * 24 * hour + 12 * hour;
20587 assert_eq!(
20588 tz_wall_to_utc_nanos("US/Eastern", wall_noon),
20589 Ok(wall_noon + 5 * hour)
20590 );
20591 assert_eq!(
20592 tz_utc_to_wall_nanos("US/Eastern", wall_noon + 5 * hour),
20593 Ok(wall_noon)
20594 );
20595 assert_eq!(tz_wall_to_utc_nanos("US/Eastern", i64::MIN), Ok(i64::MIN));
20597 assert_eq!(tz_utc_to_wall_nanos("US/Eastern", i64::MIN), Ok(i64::MIN));
20598 let skipped = 19_792 * 24 * hour + 2 * hour + 30 * 60_000_000_000;
20602 assert_eq!(
20603 tz_wall_to_utc_nanos("US/Eastern", skipped),
20604 Err(TimeZoneError::NonExistent("2024-03-10 02:30:00".to_owned()))
20605 );
20606 let repeated = 20_030 * 24 * hour + hour + 30 * 60_000_000_000;
20607 assert_eq!(
20608 tz_wall_to_utc_nanos("US/Eastern", repeated),
20609 Err(TimeZoneError::Ambiguous("2024-11-03 01:30:00".to_owned()))
20610 );
20611 assert_eq!(
20612 tz_offset_seconds("Mars/Olympus", 0),
20613 Err(TimeZoneError::Unknown("Mars/Olympus".to_owned()))
20614 );
20615 assert!(tz_validate("+24:00").is_err());
20616 assert!(tz_validate("+5:30").is_err());
20617 assert!(tz_validate("Europe/Paris").is_ok());
20618 assert_eq!(tz_canonical_name("+05:30").as_deref(), Ok("UTC+05:30"));
20620 assert_eq!(tz_canonical_name("UTC-03:00").as_deref(), Ok("UTC-03:00"));
20621 assert_eq!(tz_canonical_name("+00:00").as_deref(), Ok("UTC"));
20622 assert_eq!(tz_canonical_name("Z").as_deref(), Ok("UTC"));
20623 assert_eq!(tz_canonical_name("US/Eastern").as_deref(), Ok("US/Eastern"));
20624 assert_eq!(tz_abbreviation("US/Eastern", instant).as_deref(), Ok("EDT"));
20626 assert_eq!(
20627 tz_abbreviation("US/Eastern", instant - 24 * hour).as_deref(),
20628 Ok("EST")
20629 );
20630 assert_eq!(tz_abbreviation("+05:30", 0).as_deref(), Ok("UTC+05:30"));
20631 }
20632
20633 #[test]
20640 fn tz_localize_policies_follow_pandas_84w06() {
20641 use super::{
20642 AmbiguousTime as A, NonexistentTime as N, TimeZoneError,
20643 tz_wall_to_utc_nanos_with as at,
20644 };
20645 let hour = 3_600_000_000_000_i64;
20646 let minute = 60_000_000_000_i64;
20647 let skipped = 19_792 * 24 * hour + 2 * hour + 30 * minute;
20648 let transition = 19_792 * 24 * hour + 7 * hour;
20649 let zone = "America/New_York";
20650 assert_eq!(at(zone, skipped, A::Raise, N::ShiftForward), Ok(transition));
20651 assert_eq!(
20652 at(zone, skipped, A::Raise, N::ShiftBackward),
20653 Ok(transition - 1)
20654 );
20655 assert_eq!(at(zone, skipped, A::Raise, N::NaT), Ok(i64::MIN));
20656 assert_eq!(
20657 at(zone, skipped, A::Raise, N::Shift(hour)),
20658 Ok(transition + 30 * minute)
20659 );
20660 let repeated = 20_030 * 24 * hour + hour + 30 * minute;
20661 assert_eq!(
20662 at(zone, repeated, A::Earliest, N::Raise),
20663 Ok(repeated + 4 * hour)
20664 );
20665 assert_eq!(
20666 at(zone, repeated, A::Latest, N::Raise),
20667 Ok(repeated + 5 * hour)
20668 );
20669 assert_eq!(at(zone, repeated, A::NaT, N::Raise), Ok(i64::MIN));
20670 let noon = 19_723 * 24 * hour + 12 * hour;
20673 assert_eq!(at(zone, noon, A::NaT, N::NaT), Ok(noon + 5 * hour));
20674 assert_eq!(
20675 at(zone, skipped, A::NaT, N::Raise),
20676 Err(TimeZoneError::NonExistent("2024-03-10 02:30:00".to_owned()))
20677 );
20678 assert_eq!(
20679 at(zone, repeated, A::Raise, N::NaT),
20680 Err(TimeZoneError::Ambiguous("2024-11-03 01:30:00".to_owned()))
20681 );
20682 }
20683
20684 #[test]
20692 fn batch_tz_conversions_match_each_value_6pqf3() {
20693 use super::{
20694 AmbiguousTime as A, NonexistentTime as N, TimeZoneError, tz_utc_to_wall_nanos,
20695 tz_utc_to_wall_nanos_all, tz_wall_to_utc_nanos_all, tz_wall_to_utc_nanos_with,
20696 };
20697 const HOUR: i64 = 3_600_000_000_000;
20698 const MINUTE: i64 = 60_000_000_000;
20699 const DAY: i64 = 24 * HOUR;
20700 let (year_start, year_end) = (19_723 * DAY, 20_089 * DAY);
20701 let mut values: Vec<i64> = (year_start..year_end)
20702 .step_by(usize::try_from(37 * MINUTE).unwrap())
20703 .collect();
20704 for hour in (year_start..year_end).step_by(usize::try_from(HOUR).unwrap()) {
20705 values.extend([hour - 1, hour, hour + 1]);
20706 }
20707 for change_day in [19_792, 20_030, 19_813, 20_023, 19_820, 20_002] {
20708 values.extend((0..2 * 24 * 60).map(|minute| (change_day - 1) * DAY + minute * MINUTE));
20709 }
20710 let mut state = 0x2545_f491_4f6c_dd1d_u64;
20711 for _ in 0..3_000 {
20712 state = state
20713 .wrapping_mul(6_364_136_223_846_793_005)
20714 .wrapping_add(1_442_695_040_888_963_407);
20715 values.push(i64::try_from(state >> 2).unwrap() - 2_000_000_000_000_000_000);
20716 }
20717 values.extend([i64::MIN, 19_792 * DAY, i64::MIN]);
20718 let policies = [
20719 (A::NaT, N::NaT),
20720 (A::Earliest, N::ShiftForward),
20721 (A::Latest, N::ShiftBackward),
20722 (A::NaT, N::Shift(30 * MINUTE)),
20723 ];
20724 for zone in [
20725 "US/Eastern",
20726 "Europe/London",
20727 "Australia/Lord_Howe",
20728 "+05:30",
20729 "UTC",
20730 ] {
20731 let one_by_one: Result<Vec<i64>, TimeZoneError> = values
20732 .iter()
20733 .map(|&nanos| tz_utc_to_wall_nanos(zone, nanos))
20734 .collect();
20735 assert_eq!(
20736 tz_utc_to_wall_nanos_all(zone, &values),
20737 one_by_one,
20738 "{zone}"
20739 );
20740 for (ambiguous, nonexistent) in policies {
20741 let one_by_one: Result<Vec<i64>, TimeZoneError> = values
20742 .iter()
20743 .map(|&wall| tz_wall_to_utc_nanos_with(zone, wall, ambiguous, nonexistent))
20744 .collect();
20745 assert_eq!(
20746 tz_wall_to_utc_nanos_all(zone, &values, ambiguous, nonexistent),
20747 one_by_one,
20748 "{zone} {ambiguous:?} {nonexistent:?}"
20749 );
20750 }
20751 let one_by_one: Result<Vec<i64>, TimeZoneError> = values
20752 .iter()
20753 .map(|&wall| tz_wall_to_utc_nanos_with(zone, wall, A::Raise, N::Raise))
20754 .collect();
20755 assert_eq!(
20756 tz_wall_to_utc_nanos_all(zone, &values, A::Raise, N::Raise),
20757 one_by_one,
20758 "{zone} raise"
20759 );
20760 }
20761 let skipped = 19_792 * DAY + 2 * HOUR + 30 * MINUTE;
20762 let run: Vec<i64> = (0..8)
20764 .map(|step| 19_792 * DAY + HOUR + 10 * MINUTE + step * 20 * MINUTE)
20765 .collect();
20766 assert_eq!(
20767 tz_wall_to_utc_nanos_all("US/Eastern", &run, A::Raise, N::Raise),
20768 Err(TimeZoneError::NonExistent("2024-03-10 02:10:00".to_owned()))
20769 );
20770 let placed = tz_wall_to_utc_nanos_all("US/Eastern", &run, A::Raise, N::NaT).unwrap();
20771 let expected: Vec<i64> = run
20772 .iter()
20773 .enumerate()
20774 .map(|(step, &wall)| match step {
20775 0..3 => wall + 5 * HOUR,
20776 3..6 => i64::MIN,
20777 _ => wall + 4 * HOUR,
20778 })
20779 .collect();
20780 assert_eq!(placed, expected);
20781 let howe = 20_002 * DAY + 2 * HOUR + 10 * MINUTE;
20785 assert_eq!(
20786 tz_wall_to_utc_nanos_all("Australia/Lord_Howe", &[howe], A::Raise, N::ShiftForward),
20787 Ok(vec![20_002 * DAY - 8 * HOUR])
20788 );
20789 assert_eq!(
20790 tz_wall_to_utc_nanos_all("Australia/Lord_Howe", &[howe], A::Raise, N::ShiftBackward),
20791 Ok(vec![20_002 * DAY - 8 * HOUR - 30 * MINUTE - 1])
20792 );
20793 for (wall, text) in [
20794 (skipped + 500_000_000, "2024-03-10 02:30:00.500000"),
20795 (skipped + 1, "2024-03-10 02:30:00.000000001"),
20796 ] {
20797 assert_eq!(
20798 tz_wall_to_utc_nanos_all("US/Eastern", &[wall], A::Raise, N::Raise),
20799 Err(TimeZoneError::NonExistent(text.to_owned()))
20800 );
20801 }
20802 }
20803
20804 #[test]
20805 fn timestamp_display_matches_phase2_debug_format() {
20806 assert_eq!(Timestamp::from_nanos(42).to_string(), "Timestamp[42, UTC]");
20807 assert_eq!(
20808 Timestamp::from_nanos_tz(42, "US/Eastern").to_string(),
20809 "Timestamp[42, US/Eastern]"
20810 );
20811 assert_eq!(Timestamp::nat().to_string(), "NaT");
20812 }
20813
20814 #[test]
20815 fn a_naive_timestamp_cell_casts_to_its_str_srzqw() {
20816 let text = |nanos: i64| cast_scalar(&Scalar::Datetime64(nanos), DType::Utf8);
20820 let midnight = 1_711_929_600_000_000_000;
20821 assert_eq!(
20822 text(midnight),
20823 Ok(Scalar::Utf8("2024-04-01 00:00:00".into()))
20824 );
20825 assert_eq!(
20826 text(midnight + 1_000),
20827 Ok(Scalar::Utf8("2024-04-01 00:00:00.000001".into()))
20828 );
20829 assert_eq!(
20830 text(midnight + 1),
20831 Ok(Scalar::Utf8("2024-04-01 00:00:00.000000001".into()))
20832 );
20833 assert_eq!(
20834 text(-1),
20835 Ok(Scalar::Utf8("1969-12-31 23:59:59.999999999".into()))
20836 );
20837 assert_eq!(text(Timestamp::NAT), Ok(Scalar::Utf8("NaT".into())));
20838 assert_eq!(
20840 crate::timestamp_text_in_zone(midnight, "US/Eastern"),
20841 "2024-03-31 20:00:00-04:00"
20842 );
20843 }
20844
20845 #[test]
20846 fn timestamp_value_and_unit_match_pandas_l0edr() {
20847 let ts = Timestamp::from_nanos(1_000_000_123);
20848 assert_eq!(ts.value(), 1_000_000_123);
20849 assert_eq!(ts.unit(), Some("ns"));
20850
20851 let nat = Timestamp::nat();
20852 assert_eq!(nat.value(), Timestamp::NAT);
20853 assert_eq!(nat.unit(), None);
20854 }
20855
20856 #[test]
20857 fn timestamp_numpy_datetime64_materializers_match_value_twksi() {
20858 let ts = Timestamp::from_nanos(1_000_000_123);
20859 assert_eq!(ts.asm8(), ts.value());
20860 assert_eq!(ts.to_datetime64(), ts.value());
20861 assert_eq!(ts.to_numpy(), ts.value());
20862
20863 let nat = Timestamp::nat();
20864 assert_eq!(nat.asm8(), Timestamp::NAT);
20865 assert_eq!(nat.to_datetime64(), Timestamp::NAT);
20866 assert_eq!(nat.to_numpy(), Timestamp::NAT);
20867 }
20868
20869 #[test]
20870 fn timestamp_timestamp_accessor_matches_pandas_microsecond_rounding_py0h3() {
20871 assert_eq!(Timestamp::from_nanos(0).timestamp(), Ok(0.0));
20872 assert_eq!(Timestamp::from_nanos(1_500_000_000).timestamp(), Ok(1.5));
20873 assert_eq!(Timestamp::from_nanos(500).timestamp(), Ok(0.0));
20874 assert_eq!(Timestamp::from_nanos(501).timestamp(), Ok(0.000001));
20875 assert_eq!(Timestamp::from_nanos(2_500).timestamp(), Ok(0.000003));
20876
20877 assert!(matches!(
20878 Timestamp::from_nanos(-500).timestamp(),
20879 Ok(value) if value == -0.0 && value.is_sign_negative()
20880 ));
20881 assert_eq!(Timestamp::from_nanos(-2_500).timestamp(), Ok(-0.000003));
20882 assert_eq!(
20883 Timestamp::nat().timestamp(),
20884 Err(TypeError::ValueIsMissing {
20885 kind: NullKind::NaT,
20886 })
20887 );
20888 }
20889
20890 #[test]
20891 fn timestamp_roundtrips_through_serde_json() {
20892 let naive = Timestamp::from_nanos(1_700_000_000_000_000_000);
20893 let json = serde_json::to_string(&naive).expect("serialize");
20894 let back: Timestamp = serde_json::from_str(&json).expect("deserialize");
20895 assert_eq!(naive, back);
20896
20897 let tz_aware = Timestamp::from_nanos_tz(1_700_000_000_000_000_000, "US/Eastern");
20898 let json = serde_json::to_string(&tz_aware).expect("serialize");
20899 let back: Timestamp = serde_json::from_str(&json).expect("deserialize");
20900 assert_eq!(tz_aware, back);
20901 }
20902
20903 #[test]
20904 fn timestamp_is_send_and_sync() {
20905 fn assert_send_sync<T: Send + Sync>() {}
20906 assert_send_sync::<Timestamp>();
20907 }
20908
20909 #[test]
20912 fn timestamp_pre_epoch_accessors_floor_not_truncate() {
20913 let ts = Timestamp::from_nanos(-1);
20917 assert_eq!(ts.year(), Some(1969));
20918 assert_eq!(ts.month(), Some(12));
20919 assert_eq!(ts.day(), Some(31));
20920 assert_eq!(ts.hour(), Some(23));
20921 assert_eq!(ts.minute(), Some(59));
20922 assert_eq!(ts.second(), Some(59));
20923 assert_eq!(ts.microsecond(), Some(999_999));
20924 assert_eq!(ts.nanosecond(), Some(999));
20925 assert_eq!(ts.dayofweek(), Some(2));
20927
20928 let noon = Timestamp::from_nanos(-43200 * Timedelta::NANOS_PER_SEC);
20930 assert_eq!(noon.year(), Some(1969));
20931 assert_eq!(noon.month(), Some(12));
20932 assert_eq!(noon.day(), Some(31));
20933 assert_eq!(noon.hour(), Some(12));
20934
20935 let midnight = Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY);
20937 assert_eq!(midnight.year(), Some(1969));
20938 assert_eq!(midnight.day(), Some(31));
20939 assert_eq!(midnight.hour(), Some(0));
20940 }
20941
20942 #[test]
20943 fn timestamp_floor_to_rounds_down() {
20944 let h = Timedelta::NANOS_PER_HOUR;
20946 let twelve_h = h * 12;
20947 let twelve_thirty_four =
20948 twelve_h + Timedelta::NANOS_PER_MIN * 34 + Timedelta::NANOS_PER_SEC * 56;
20949 let ts = Timestamp::from_nanos(twelve_thirty_four);
20950 let floored = ts.floor_to(h);
20951 assert_eq!(floored.nanos, twelve_h);
20952 }
20953
20954 #[test]
20955 fn timestamp_floor_to_handles_already_aligned() {
20956 let h = Timedelta::NANOS_PER_HOUR;
20958 let twelve_h = h * 12;
20959 let ts = Timestamp::from_nanos(twelve_h);
20960 assert_eq!(ts.floor_to(h).nanos, twelve_h);
20961 }
20962
20963 #[test]
20964 fn timestamp_floor_to_handles_negative_nanos() {
20965 let ts = Timestamp::from_nanos(-100);
20969 assert_eq!(ts.floor_to(60).nanos, -120);
20970 }
20971
20972 #[test]
20973 fn timestamp_floor_to_returns_nat_on_axis_underflow_30hdi() {
20974 let ts = Timestamp::from_nanos(i64::MIN + 1);
20975 assert!(ts.floor_to(10).is_nat());
20976
20977 let safe = Timestamp::from_nanos(i64::MIN + 10);
20978 assert_eq!(safe.floor_to(10).nanos, i64::MIN + 8);
20979
20980 let tz = Timestamp::from_nanos_tz(-100, "UTC").floor_to(60);
20981 assert_eq!(tz.nanos, -120);
20982 assert_eq!(tz.tz.as_deref(), Some("UTC"));
20983 }
20984
20985 #[test]
20986 fn timestamp_ceil_to_rounds_up() {
20987 let h = Timedelta::NANOS_PER_HOUR;
20989 let twelve_h = h * 12;
20990 let thirteen_h = h * 13;
20991 let twelve_thirty_four =
20992 twelve_h + Timedelta::NANOS_PER_MIN * 34 + Timedelta::NANOS_PER_SEC * 56;
20993 let ts = Timestamp::from_nanos(twelve_thirty_four);
20994 assert_eq!(ts.ceil_to(h).nanos, thirteen_h);
20995 }
20996
20997 #[test]
20998 fn timestamp_ceil_to_no_op_on_aligned() {
20999 let h = Timedelta::NANOS_PER_HOUR;
21000 let twelve_h = h * 12;
21001 let ts = Timestamp::from_nanos(twelve_h);
21002 assert_eq!(ts.ceil_to(h).nanos, twelve_h);
21003 }
21004
21005 #[test]
21006 fn timestamp_round_to_rounds_to_nearest() {
21007 let h = Timedelta::NANOS_PER_HOUR;
21009 let twelve_h = h * 12;
21010 let twelve_thirty_one_sec =
21011 twelve_h + Timedelta::NANOS_PER_MIN * 30 + Timedelta::NANOS_PER_SEC;
21012 let ts = Timestamp::from_nanos(twelve_thirty_one_sec);
21013 assert_eq!(ts.round_to(h).nanos, h * 13);
21014
21015 let twelve_twenty_nine_sec =
21017 twelve_h + Timedelta::NANOS_PER_MIN * 29 + Timedelta::NANOS_PER_SEC * 59;
21018 let ts = Timestamp::from_nanos(twelve_twenty_nine_sec);
21019 assert_eq!(ts.round_to(h).nanos, twelve_h);
21020 }
21021
21022 #[test]
21023 fn timestamp_round_to_bankers_tie_to_even() {
21024 assert_eq!(Timestamp::from_nanos(5).round_to(10).nanos, 0);
21030 assert_eq!(Timestamp::from_nanos(15).round_to(10).nanos, 20);
21031 assert_eq!(Timestamp::from_nanos(25).round_to(10).nanos, 20);
21032 assert_eq!(Timestamp::from_nanos(35).round_to(10).nanos, 40);
21033 }
21034
21035 #[test]
21036 fn timestamp_round_to_zero_unit_returns_nat() {
21037 let ts = Timestamp::from_nanos(100);
21038 assert!(ts.round_to(0).is_nat());
21039 assert!(ts.floor_to(0).is_nat());
21040 assert!(ts.ceil_to(0).is_nat());
21041 }
21042
21043 #[test]
21044 fn timestamp_round_to_negative_unit_returns_nat() {
21045 let ts = Timestamp::from_nanos(100);
21046 assert!(ts.round_to(-10).is_nat());
21047 assert!(ts.floor_to(-10).is_nat());
21048 assert!(ts.ceil_to(-10).is_nat());
21049 }
21050
21051 #[test]
21052 fn timestamp_rounding_propagates_nat() {
21053 let nat = Timestamp::nat();
21054 assert!(nat.floor_to(60).is_nat());
21055 assert!(nat.ceil_to(60).is_nat());
21056 assert!(nat.round_to(60).is_nat());
21057 }
21058
21059 #[test]
21060 fn timestamp_rounding_preserves_tz() {
21061 let ts = Timestamp::from_nanos_tz(100, "US/Eastern");
21062 assert_eq!(ts.floor_to(60).tz.as_deref(), Some("US/Eastern"));
21063 assert_eq!(ts.ceil_to(60).tz.as_deref(), Some("US/Eastern"));
21064 assert_eq!(ts.round_to(60).tz.as_deref(), Some("US/Eastern"));
21065 }
21066
21067 #[test]
21070 fn timestamp_floor_to_unit_h_rounds_to_hour() {
21071 let h = Timedelta::NANOS_PER_HOUR;
21072 let twelve_h = h * 12;
21073 let twelve_thirty_four =
21074 twelve_h + Timedelta::NANOS_PER_MIN * 34 + Timedelta::NANOS_PER_SEC * 56;
21075 let ts = Timestamp::from_nanos(twelve_thirty_four);
21076 assert_eq!(ts.floor_to_unit("H").nanos, twelve_h);
21077 assert_eq!(ts.floor_to_unit("h").nanos, twelve_h);
21078 assert_eq!(ts.floor_to_unit("hour").nanos, twelve_h);
21079 assert_eq!(ts.floor_to_unit("hours").nanos, twelve_h);
21080 assert_eq!(ts.floor_to_unit("hr").nanos, twelve_h);
21081 }
21082
21083 #[test]
21084 fn timestamp_ceil_to_unit_d_rounds_to_day() {
21085 let h = Timedelta::NANOS_PER_HOUR;
21087 let d = Timedelta::NANOS_PER_DAY;
21088 let twelve_thirty_four = h * 12 + Timedelta::NANOS_PER_MIN * 34;
21089 let ts = Timestamp::from_nanos(twelve_thirty_four);
21090 assert_eq!(ts.ceil_to_unit("D").nanos, d);
21091 assert_eq!(ts.ceil_to_unit("day").nanos, d);
21092 assert_eq!(ts.ceil_to_unit("days").nanos, d);
21093 }
21094
21095 #[test]
21096 fn timestamp_round_to_unit_min_rounds_to_minute() {
21097 let m = Timedelta::NANOS_PER_MIN;
21099 let twelve_thirty_four_thirty_one =
21100 Timedelta::NANOS_PER_HOUR * 12 + m * 34 + Timedelta::NANOS_PER_SEC * 31;
21101 let ts = Timestamp::from_nanos(twelve_thirty_four_thirty_one);
21102 let expected = Timedelta::NANOS_PER_HOUR * 12 + m * 35;
21103 assert_eq!(ts.round_to_unit("min").nanos, expected);
21104 assert_eq!(ts.round_to_unit("T").nanos, expected); assert_eq!(ts.round_to_unit("minute").nanos, expected);
21106 }
21107
21108 #[test]
21109 fn timestamp_floor_ceil_round_aliases_match_unit_methods_li897() {
21110 let ts = Timestamp::from_nanos(
21111 Timedelta::NANOS_PER_HOUR * 12
21112 + Timedelta::NANOS_PER_MIN * 34
21113 + Timedelta::NANOS_PER_SEC * 31,
21114 );
21115
21116 assert_eq!(ts.floor("H"), ts.floor_to_unit("H"));
21117 assert_eq!(ts.ceil("D"), ts.ceil_to_unit("D"));
21118 assert_eq!(ts.round("min"), ts.round_to_unit("min"));
21119 }
21120
21121 #[test]
21122 fn timestamp_normalize_floors_to_day_and_preserves_tz_455op() {
21123 let ts = Timestamp::from_nanos_tz(
21124 Timedelta::NANOS_PER_DAY * 3
21125 + Timedelta::NANOS_PER_HOUR * 12
21126 + Timedelta::NANOS_PER_MIN * 34,
21127 "US/Eastern",
21128 );
21129 let normalized = ts.normalize();
21130
21131 assert_eq!(normalized.nanos, Timedelta::NANOS_PER_DAY * 3);
21132 assert_eq!(normalized.tz.as_deref(), Some("US/Eastern"));
21133 assert!(Timestamp::nat().normalize().is_nat());
21134 for nanos in [
21135 i64::MIN + 1,
21136 -Timedelta::NANOS_PER_DAY - 1,
21137 -Timedelta::NANOS_PER_DAY,
21138 -1,
21139 0,
21140 Timedelta::NANOS_PER_DAY - 1,
21141 Timedelta::NANOS_PER_DAY,
21142 i64::MAX,
21143 ] {
21144 let timestamp = Timestamp::from_nanos(nanos);
21145 assert_eq!(timestamp.normalize(), timestamp.floor_to_unit("D"));
21146 }
21147 }
21148
21149 #[test]
21150 #[ignore = "foreground profile-first A/B"]
21151 fn timestamp_normalize_direct_day_profile_dk721() {
21152 use std::{hint::black_box, time::Instant};
21153
21154 fn former(timestamp: &Timestamp) -> Timestamp {
21155 timestamp.floor_to_unit("D")
21156 }
21157
21158 fn candidate(timestamp: &Timestamp) -> Timestamp {
21159 timestamp.normalize()
21160 }
21161
21162 fn elapsed(input: &[Timestamp], normalize: impl Fn(&Timestamp) -> Timestamp) -> u128 {
21163 let started = Instant::now();
21164 let mut checksum = 0_u64;
21165 for timestamp in input {
21166 let normalized = normalize(black_box(timestamp));
21167 checksum = checksum.rotate_left(7) ^ normalized.nanos as u64;
21168 }
21169 black_box(checksum);
21170 started.elapsed().as_nanos()
21171 }
21172
21173 fn percentile(samples: &mut [u128], percent: usize) -> u128 {
21174 samples.sort_unstable();
21175 let rank = (samples.len() * percent).div_ceil(100).saturating_sub(1);
21176 samples[rank]
21177 }
21178
21179 let parity_cases = [
21180 Timestamp::nat(),
21181 Timestamp::from_nanos(i64::MIN + 1),
21182 Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY - 1),
21183 Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY),
21184 Timestamp::from_nanos(-1),
21185 Timestamp::from_nanos(0),
21186 Timestamp::from_nanos(Timedelta::NANOS_PER_DAY - 1),
21187 Timestamp::from_nanos(Timedelta::NANOS_PER_DAY),
21188 Timestamp::from_nanos(i64::MAX),
21189 Timestamp::from_nanos_tz(-1, "US/Eastern"),
21190 Timestamp::from_nanos_tz(
21191 Timedelta::NANOS_PER_DAY + Timedelta::NANOS_PER_HOUR,
21192 "Asia/Tokyo",
21193 ),
21194 ];
21195 for timestamp in &parity_cases {
21196 assert_eq!(former(timestamp), candidate(timestamp));
21197 assert_eq!(timestamp.normalize(), former(timestamp));
21198 }
21199
21200 const ROWS: usize = 16_384;
21201 const SAMPLES: usize = 20;
21202 let input = (0..ROWS)
21203 .map(|index| {
21204 let day = index as i64 % 4_096 - 2_048;
21205 let offset = ((index as u64).wrapping_mul(6_364_136_223_846_793_005_u64)
21206 % Timedelta::NANOS_PER_DAY as u64) as i64;
21207 Timestamp::from_nanos(day * Timedelta::NANOS_PER_DAY + offset)
21208 })
21209 .collect::<Vec<_>>();
21210 for timestamp in &input {
21211 assert_eq!(former(timestamp), candidate(timestamp));
21212 }
21213
21214 for _ in 0..3 {
21215 black_box(elapsed(&input, former));
21216 black_box(elapsed(&input, candidate));
21217 }
21218
21219 let mut former_ns = Vec::with_capacity(SAMPLES);
21220 let mut candidate_ns = Vec::with_capacity(SAMPLES);
21221 for sample in 0..SAMPLES {
21222 if sample % 2 == 0 {
21223 former_ns.push(elapsed(&input, former));
21224 candidate_ns.push(elapsed(&input, candidate));
21225 } else {
21226 candidate_ns.push(elapsed(&input, candidate));
21227 former_ns.push(elapsed(&input, former));
21228 }
21229 }
21230
21231 let mut former_sorted = former_ns.clone();
21232 let mut candidate_sorted = candidate_ns.clone();
21233 let former_p50 = percentile(&mut former_sorted, 50);
21234 let former_p95 = percentile(&mut former_sorted, 95);
21235 let former_p99 = percentile(&mut former_sorted, 99);
21236 let candidate_p50 = percentile(&mut candidate_sorted, 50);
21237 let candidate_p95 = percentile(&mut candidate_sorted, 95);
21238 let candidate_p99 = percentile(&mut candidate_sorted, 99);
21239 println!(
21240 "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:?}",
21241 former_p50 as f64 / candidate_p50 as f64,
21242 former_p95 as f64 / candidate_p95 as f64,
21243 former_p99 as f64 / candidate_p99 as f64,
21244 );
21245 }
21246
21247 #[test]
21248 fn timestamp_unit_rounding_unknown_unit_returns_nat() {
21249 let ts = Timestamp::from_nanos(100);
21250 assert!(ts.floor_to_unit("fortnight").is_nat());
21251 assert!(ts.ceil_to_unit("century").is_nat());
21252 assert!(ts.round_to_unit("xyz").is_nat());
21253 }
21254
21255 #[test]
21258 fn timestamp_rounding_reads_a_multiple_of_a_unit_3agof() {
21259 let (min, sec) = (Timedelta::NANOS_PER_MIN, Timedelta::NANOS_PER_SEC);
21260 let base = 1_710_460_800 * sec; let ts = Timestamp::from_nanos(base + 13 * Timedelta::NANOS_PER_HOUR + 47 * min + 21 * sec);
21262 let at = |minutes: i64, seconds: i64| base + minutes * min + seconds * sec;
21263 assert_eq!(ts.round("15min").nanos, at(13 * 60 + 45, 0));
21264 assert_eq!(ts.floor("15min").nanos, at(13 * 60 + 45, 0));
21265 assert_eq!(ts.ceil("15min").nanos, at(14 * 60, 0));
21266 assert_eq!(ts.round("30s").nanos, at(13 * 60 + 47, 30));
21267 assert_eq!(ts.ceil("1D").nanos, base + Timedelta::NANOS_PER_DAY);
21268 assert_eq!(ts.floor("7D").nanos, 19_796 * Timedelta::NANOS_PER_DAY);
21271 assert!(ts.round("ME").is_nat());
21273 }
21274
21275 #[test]
21276 fn timestamp_unit_rounding_propagates_nat() {
21277 let nat = Timestamp::nat();
21278 assert!(nat.floor_to_unit("H").is_nat());
21279 assert!(nat.ceil_to_unit("H").is_nat());
21280 assert!(nat.round_to_unit("H").is_nat());
21281 }
21282
21283 #[test]
21284 fn timestamp_unit_rounding_preserves_tz() {
21285 let ts = Timestamp::from_nanos_tz(Timedelta::NANOS_PER_HOUR * 12 + 100, "US/Eastern");
21286 assert_eq!(ts.floor_to_unit("H").tz.as_deref(), Some("US/Eastern"));
21287 assert_eq!(ts.ceil_to_unit("H").tz.as_deref(), Some("US/Eastern"));
21288 assert_eq!(ts.round_to_unit("H").tz.as_deref(), Some("US/Eastern"));
21289 }
21290
21291 #[test]
21292 fn timedelta_unit_to_nanos_is_now_public_and_matches_pandas_aliases() {
21293 assert_eq!(
21295 Timedelta::unit_to_nanos("W"),
21296 Some(Timedelta::NANOS_PER_WEEK)
21297 );
21298 assert_eq!(
21299 Timedelta::unit_to_nanos("D"),
21300 Some(Timedelta::NANOS_PER_DAY)
21301 );
21302 assert_eq!(
21303 Timedelta::unit_to_nanos("H"),
21304 Some(Timedelta::NANOS_PER_HOUR)
21305 );
21306 assert_eq!(
21307 Timedelta::unit_to_nanos("min"),
21308 Some(Timedelta::NANOS_PER_MIN)
21309 );
21310 assert_eq!(
21311 Timedelta::unit_to_nanos("s"),
21312 Some(Timedelta::NANOS_PER_SEC)
21313 );
21314 assert_eq!(
21315 Timedelta::unit_to_nanos("ms"),
21316 Some(Timedelta::NANOS_PER_MILLI)
21317 );
21318 assert_eq!(
21319 Timedelta::unit_to_nanos("us"),
21320 Some(Timedelta::NANOS_PER_MICRO)
21321 );
21322 assert_eq!(Timedelta::unit_to_nanos("ns"), Some(1));
21323 assert_eq!(Timedelta::unit_to_nanos(""), Some(Timedelta::NANOS_PER_DAY));
21325 assert_eq!(Timedelta::unit_to_nanos("century"), None);
21327 }
21328
21329 #[test]
21330 fn timestamp_isoformat_basic() {
21331 let ts = Timestamp::from_nanos(0);
21332 assert_eq!(ts.isoformat(), "1970-01-01T00:00:00");
21333
21334 let ts_utc = Timestamp::from_nanos_tz(0, "UTC");
21335 assert_eq!(ts_utc.isoformat(), "1970-01-01T00:00:00+00:00");
21336
21337 let ts_fixed_offset = Timestamp::from_nanos_tz(0, "UTC+05:30");
21338 assert_eq!(
21339 ts_fixed_offset.isoformat(),
21340 "1970-01-01T05:30:00+05:30",
21341 "a fixed-offset timestamp must render local wall time rather than a UTC instant with an annotation"
21342 );
21343
21344 let ts_tz = Timestamp::from_nanos_tz(
21345 Timedelta::NANOS_PER_DAY
21346 + Timedelta::NANOS_PER_HOUR * 14
21347 + Timedelta::NANOS_PER_MIN * 30,
21348 "America/New_York",
21349 );
21350 assert_eq!(ts_tz.isoformat(), "1970-01-02T09:30:00-05:00");
21351
21352 assert_eq!(Timestamp::nat().isoformat(), "NaT");
21353 }
21354
21355 #[test]
21356 fn timestamp_isoformat_pre_epoch_subsecond_uses_floor_day_263m5() {
21357 assert_eq!(
21358 Timestamp::from_nanos(-1).isoformat(),
21359 "1969-12-31T23:59:59.999999999"
21360 );
21361 assert_eq!(
21362 Timestamp::from_nanos(-Timedelta::NANOS_PER_SEC).isoformat(),
21363 "1969-12-31T23:59:59"
21364 );
21365 assert_eq!(
21366 Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY).isoformat(),
21367 "1969-12-31T00:00:00"
21368 );
21369 assert_eq!(
21370 Timestamp::from_nanos_tz(-1, "UTC").isoformat(),
21371 "1969-12-31T23:59:59.999999999+00:00"
21372 );
21373 }
21374
21375 #[test]
21376 fn timestamp_isoformat_preserves_nanosecond_fraction_4r99y() {
21377 assert_eq!(
21378 Timestamp::from_nanos(123_456_789).isoformat(),
21379 "1970-01-01T00:00:00.123456789"
21380 );
21381 assert_eq!(
21382 Timestamp::from_nanos(123_456_000).isoformat(),
21383 "1970-01-01T00:00:00.123456"
21384 );
21385 assert_eq!(
21386 Timestamp::from_nanos(123_000_000).isoformat(),
21387 "1970-01-01T00:00:00.123000"
21388 );
21389 assert_eq!(
21390 Timestamp::from_nanos_tz(1, "UTC").isoformat(),
21391 "1970-01-01T00:00:00.000000001+00:00"
21392 );
21393 }
21394
21395 fn timestamp_isoformat_former_q8g50(timestamp: &Timestamp) -> String {
21396 if timestamp.is_nat() {
21397 return "NaT".to_owned();
21398 }
21399 let Some(tz) = ×tamp.tz else {
21400 return Timestamp::from_nanos(timestamp.nanos).isoformat();
21401 };
21402 if let Ok(offset_secs) = crate::tz_offset_seconds(tz, timestamp.nanos)
21403 && let Some(display_nanos) = timestamp
21404 .nanos
21405 .checked_add(i64::from(offset_secs) * Timedelta::NANOS_PER_SEC)
21406 {
21407 let base = Timestamp::from_nanos(display_nanos).isoformat();
21408 let sign = if offset_secs < 0 { '-' } else { '+' };
21409 let total_minutes = offset_secs.unsigned_abs() / 60;
21410 return format!(
21411 "{base}{sign}{:02}:{:02}",
21412 total_minutes / 60,
21413 total_minutes % 60
21414 );
21415 }
21416 let base = Timestamp::from_nanos(timestamp.nanos).isoformat();
21417 format!("{base}[{tz}]")
21418 }
21419
21420 #[test]
21421 fn timestamp_isoformat_one_buffer_matches_former_q8g50() {
21422 let nanos = [
21423 Timestamp::NAT,
21424 -Timedelta::NANOS_PER_DAY - 1,
21425 -Timedelta::NANOS_PER_SEC,
21426 -1,
21427 0,
21428 1,
21429 123_456_000,
21430 123_456_789,
21431 i64::MAX,
21432 ];
21433 let timezones = [
21434 None,
21435 Some("UTC"),
21436 Some("America/New_York"),
21437 Some(""),
21438 Some("Etc/Γ"),
21439 ];
21440 for value in nanos {
21441 for timezone in timezones {
21442 let timestamp = Timestamp {
21443 nanos: value,
21444 tz: timezone.map(str::to_owned),
21445 };
21446 assert_eq!(
21447 timestamp.isoformat(),
21448 timestamp_isoformat_former_q8g50(×tamp),
21449 "nanos={value} timezone={timezone:?}"
21450 );
21451 }
21452 }
21453 }
21454
21455 #[test]
21456 #[ignore = "foreground release A/B only"]
21457 fn timestamp_isoformat_one_buffer_ab_q8g50() {
21458 use std::{hint::black_box, time::Instant};
21459
21460 const ITEMS: usize = 8_192;
21461 const SAMPLES: usize = 10;
21462
21463 fn elapsed(values: &[Timestamp], render: fn(&Timestamp) -> String) -> u128 {
21464 let started = Instant::now();
21465 let mut checksum = 0usize;
21466 for timestamp in black_box(values) {
21467 checksum = checksum.wrapping_add(black_box(render(black_box(timestamp))).len());
21468 }
21469 black_box(checksum);
21470 started.elapsed().as_nanos()
21471 }
21472
21473 let values = (0..ITEMS)
21474 .map(|idx| {
21475 let nanos = (idx as i64 - ITEMS as i64 / 2) * 1_000_123_456_789;
21476 let timezone = if idx.is_multiple_of(2) {
21477 "UTC"
21478 } else {
21479 "America/New_York"
21480 };
21481 Timestamp::from_nanos_tz(nanos, timezone)
21482 })
21483 .collect::<Vec<_>>();
21484 for timestamp in &values {
21485 assert_eq!(
21486 timestamp.isoformat(),
21487 timestamp_isoformat_former_q8g50(timestamp)
21488 );
21489 }
21490
21491 black_box(elapsed(&values, timestamp_isoformat_former_q8g50));
21492 black_box(elapsed(&values, Timestamp::isoformat));
21493
21494 let mut former_ns = Vec::with_capacity(SAMPLES);
21495 let mut one_buffer_ns = Vec::with_capacity(SAMPLES);
21496 for sample in 0..SAMPLES {
21497 if sample.is_multiple_of(2) {
21498 former_ns.push(elapsed(&values, timestamp_isoformat_former_q8g50));
21499 one_buffer_ns.push(elapsed(&values, Timestamp::isoformat));
21500 } else {
21501 one_buffer_ns.push(elapsed(&values, Timestamp::isoformat));
21502 former_ns.push(elapsed(&values, timestamp_isoformat_former_q8g50));
21503 }
21504 }
21505 former_ns.sort_unstable();
21506 one_buffer_ns.sort_unstable();
21507 let former_p50 = former_ns[SAMPLES / 2];
21508 let one_buffer_p50 = one_buffer_ns[SAMPLES / 2];
21509 println!(
21510 "timestamp_isoformat_one_buffer_ab items={ITEMS} samples={SAMPLES} former_p50_ns={former_p50} one_buffer_p50_ns={one_buffer_p50} speedup={:.6}x",
21511 former_p50 as f64 / one_buffer_p50 as f64
21512 );
21513 println!("former_samples_ns={former_ns:?}");
21514 println!("one_buffer_samples_ns={one_buffer_ns:?}");
21515 }
21516
21517 #[test]
21518 fn timestamp_strftime_basic() {
21519 let ts = Timestamp::from_nanos(
21520 Timedelta::NANOS_PER_DAY * 365
21521 + Timedelta::NANOS_PER_HOUR * 9
21522 + Timedelta::NANOS_PER_MIN * 15,
21523 );
21524 assert_eq!(ts.strftime("%Y-%m-%d"), "1971-01-01");
21525 assert_eq!(ts.strftime("%H:%M:%S"), "09:15:00");
21526 assert_eq!(ts.strftime("%Y/%m/%d %H:%M"), "1971/01/01 09:15");
21527 assert_eq!(ts.strftime("%%Y|%%%m|%Q|%|λ"), "%Y|%01|%Q|%|λ");
21530 assert_eq!(Timestamp::nat().strftime("%Y-%m-%d"), "NaT");
21531 }
21532
21533 #[test]
21534 fn strftime_follows_python_directives_and_zones() {
21535 let ts = Timestamp::from_nanos(
21538 Timedelta::NANOS_PER_DAY * 365
21539 + Timedelta::NANOS_PER_HOUR * 9
21540 + Timedelta::NANOS_PER_MIN * 15,
21541 );
21542 assert_eq!(
21543 ts.strftime("%-d %_m %^a %e %k %l %P %C %g %D %F %T %R %r %h %n %t|"),
21544 "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|"
21545 );
21546 assert_eq!(
21547 ts.strftime("%a %A %b %B %c|%x %X|%I %p %j %U %W %w %y"),
21548 "Fri Friday Jan January Fri Jan 1 09:15:00 1971|01/01/71 09:15:00|09 AM 001 00 00 5 71"
21549 );
21550 let sunday = Timestamp::parse("2021-01-03").expect("date");
21552 assert_eq!(sunday.strftime("%G-%V-%u %U %W %j"), "2020-53-7 01 00 003");
21553 let fraction = Timestamp::parse("2024-03-05 14:07:09.123456789").expect("ts");
21555 assert_eq!(fraction.strftime("%f|%z|%Z|abc%"), "123456|||abc%");
21556 let eastern = Timestamp::from_nanos_tz(fraction.nanos, "US/Eastern");
21558 assert_eq!(
21559 eastern.strftime("%Y-%m-%d %H:%M %z %Z"),
21560 "2024-03-05 09:07 -0500 EST"
21561 );
21562 assert_eq!(
21563 crate::strftime_in_zone(fraction.nanos, "%H:%M %z", Some("+05:30")),
21564 "19:37 +0530"
21565 );
21566 }
21567
21568 #[test]
21569 fn timestamp_strftime_floors_pre_epoch_instants_1pmlp() {
21570 let apollo = Timestamp::parse("1969-07-20T20:17:40").unwrap();
21571 assert_eq!(
21572 apollo.strftime("%Y-%m-%d %H:%M:%S.%f"),
21573 "1969-07-20 20:17:40.000000"
21574 );
21575
21576 let one_ns_before_epoch = Timestamp::from_nanos(-1);
21579 assert_eq!(
21580 one_ns_before_epoch.strftime("%Y-%m-%d %H:%M:%S.%f"),
21581 "1969-12-31 23:59:59.999999"
21582 );
21583 }
21584
21585 #[test]
21586 #[ignore = "foreground normal-release attribution harness"]
21587 fn timestamp_strftime_one_buffer_profile_8qzbo() {
21588 use std::{hint::black_box, time::Instant};
21589
21590 const ITEMS: usize = 8_192;
21591 const SAMPLES: usize = 10;
21592 const FORMAT: &str = "%Y-%m-%d %H:%M:%S.%f|%Y%m%d|%%Y|λ%Q";
21593
21594 fn former(timestamp: &Timestamp, format: &str) -> String {
21595 if timestamp.is_nat() {
21596 return "NaT".to_string();
21597 }
21598 let total_secs = timestamp.nanos / Timedelta::NANOS_PER_SEC;
21599 let sub_nanos = timestamp.nanos.rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
21600
21601 let days_since_epoch = total_secs / 86400;
21602 let secs_of_day = (total_secs % 86400 + 86400) % 86400;
21603 let days = days_since_epoch + 719_468;
21604 let era = (if days >= 0 { days } else { days - 146_096 }) / 146_097;
21605 let doe = days - era * 146_097;
21606 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
21607 let y = yoe + era * 400;
21608 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
21609 let mp = (5 * doy + 2) / 153;
21610 let d = doy - (153 * mp + 2) / 5 + 1;
21611 let m = if mp < 10 { mp + 3 } else { mp - 9 };
21612 let year = if m <= 2 { y + 1 } else { y };
21613 let hour = secs_of_day / 3600;
21614 let minute = (secs_of_day % 3600) / 60;
21615 let second = secs_of_day % 60;
21616 let micros = sub_nanos / 1000;
21617
21618 format
21619 .replace("%Y", &format!("{year:04}"))
21620 .replace("%m", &format!("{m:02}"))
21621 .replace("%d", &format!("{d:02}"))
21622 .replace("%H", &format!("{hour:02}"))
21623 .replace("%M", &format!("{minute:02}"))
21624 .replace("%S", &format!("{second:02}"))
21625 .replace("%f", &format!("{micros:06}"))
21626 }
21627
21628 fn elapsed(timestamps: &[Timestamp], formatter: fn(&Timestamp, &str) -> String) -> u128 {
21629 let started = Instant::now();
21630 let mut digest = 0_usize;
21631 for timestamp in timestamps {
21632 let value = formatter(black_box(timestamp), black_box(FORMAT));
21633 digest = digest.wrapping_add(value.len());
21634 digest ^= usize::from(value.as_bytes().first().copied().unwrap_or_default());
21635 black_box(value);
21636 }
21637 black_box(digest);
21638 started.elapsed().as_nanos()
21639 }
21640
21641 fn percentile(samples: &mut [u128], pct: usize) -> u128 {
21642 samples.sort_unstable();
21643 let rank = (samples.len() * pct).div_ceil(100).saturating_sub(1);
21644 samples[rank]
21645 }
21646
21647 let edge_timestamps = [
21648 Timestamp::nat(),
21649 Timestamp::from_nanos(i64::MIN + 1),
21650 Timestamp::from_nanos(-1_234_567_890),
21651 Timestamp::from_nanos(0),
21652 Timestamp::from_nanos(1_735_732_800_123_456_789),
21653 Timestamp::from_nanos(i64::MAX),
21654 ];
21655 let edge_formats = [
21656 "",
21657 "%Y-%m-%d %H:%M:%S.%f",
21658 "%Y%Y%m%m%d%d%H%H%M%M%S%S%f%f",
21659 "%%Y|%%%m|%Q|%|λ",
21660 FORMAT,
21661 ];
21662 for timestamp in &edge_timestamps {
21663 for format in edge_formats {
21664 assert_eq!(former(timestamp, format), timestamp.strftime(format));
21665 }
21666 }
21667
21668 let timestamps = (0..ITEMS)
21669 .map(|index| {
21670 let centered = index as i64 - ITEMS as i64 / 2;
21671 Timestamp::from_nanos(centered * 987_654_321_123_456)
21672 })
21673 .collect::<Vec<_>>();
21674 for timestamp in ×tamps {
21675 assert_eq!(former(timestamp, FORMAT), timestamp.strftime(FORMAT));
21676 }
21677
21678 black_box(elapsed(×tamps, former));
21679 black_box(elapsed(×tamps, Timestamp::strftime));
21680
21681 let mut former_samples = Vec::with_capacity(SAMPLES);
21682 let mut public_samples = Vec::with_capacity(SAMPLES);
21683 for sample in 0..SAMPLES {
21684 if sample.is_multiple_of(2) {
21685 former_samples.push(elapsed(×tamps, former));
21686 public_samples.push(elapsed(×tamps, Timestamp::strftime));
21687 } else {
21688 public_samples.push(elapsed(×tamps, Timestamp::strftime));
21689 former_samples.push(elapsed(×tamps, former));
21690 }
21691 }
21692 let former_p50 = percentile(&mut former_samples, 50);
21693 let former_p95 = percentile(&mut former_samples, 95);
21694 let public_p50 = percentile(&mut public_samples, 50);
21695 let public_p95 = percentile(&mut public_samples, 95);
21696 println!(
21697 "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}",
21698 former_p50 as f64 / public_p50 as f64,
21699 former_p95 as f64 / public_p95 as f64,
21700 );
21701 println!("TIMESTAMP_STRFTIME_AB former_samples_ns={former_samples:?}");
21702 println!("TIMESTAMP_STRFTIME_AB public_samples_ns={public_samples:?}");
21703 }
21704
21705 #[test]
21706 fn timestamp_day_name_and_month_name() {
21707 let ts = Timestamp::from_nanos(0);
21708 assert_eq!(ts.day_name(), "Thursday");
21709 assert_eq!(ts.month_name(), "January");
21710
21711 let ts2 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 365);
21712 assert_eq!(ts2.day_name(), "Friday");
21713 assert_eq!(ts2.month_name(), "January");
21714
21715 assert_eq!(Timestamp::nat().day_name(), "NaT");
21716 assert_eq!(Timestamp::nat().month_name(), "NaT");
21717 }
21718
21719 #[test]
21720 fn timestamp_replace_validates_components_zw0y2() {
21721 let ts = Timestamp::parse("2024-01-15T10:30:45.123456789").unwrap();
21722 let replaced = ts.replace(
21723 Some(2024),
21724 Some(2),
21725 Some(29),
21726 Some(23),
21727 Some(59),
21728 Some(58),
21729 Some(987_654),
21730 Some(321),
21731 );
21732 assert_eq!(replaced.year(), Some(2024));
21733 assert_eq!(replaced.month(), Some(2));
21734 assert_eq!(replaced.day(), Some(29));
21735 assert_eq!(replaced.hour(), Some(23));
21736 assert_eq!(replaced.minute(), Some(59));
21737 assert_eq!(replaced.second(), Some(58));
21738 assert_eq!(replaced.microsecond(), Some(987_654));
21739 assert_eq!(replaced.nanosecond(), Some(321));
21740
21741 let tz = Timestamp::from_nanos_tz(ts.nanos, "UTC");
21742 assert_eq!(
21743 tz.replace(None, Some(2), Some(29), None, None, None, None, None)
21744 .tz
21745 .as_deref(),
21746 Some("UTC")
21747 );
21748
21749 assert!(
21750 ts.replace(None, Some(13), None, None, None, None, None, None)
21751 .is_nat()
21752 );
21753 assert!(
21754 ts.replace(Some(2023), Some(2), Some(29), None, None, None, None, None)
21755 .is_nat()
21756 );
21757 assert!(
21758 ts.replace(None, None, None, Some(24), None, None, None, None)
21759 .is_nat()
21760 );
21761 assert!(
21762 ts.replace(None, None, None, None, Some(60), None, None, None)
21763 .is_nat()
21764 );
21765 assert!(
21766 ts.replace(None, None, None, None, None, Some(60), None, None)
21767 .is_nat()
21768 );
21769 assert!(
21770 ts.replace(None, None, None, None, None, None, Some(1_000_000), None)
21771 .is_nat()
21772 );
21773 assert!(
21774 ts.replace(None, None, None, None, None, None, None, Some(1_000))
21775 .is_nat()
21776 );
21777 assert!(
21778 Timestamp::nat()
21779 .replace(Some(2024), Some(1), Some(1), None, None, None, None, None)
21780 .is_nat()
21781 );
21782 }
21783
21784 #[test]
21791 fn timestamp_replace_returns_nat_on_nanosecond_overflow_dzz6x() {
21792 let ts = Timestamp::parse("2024-01-15T10:30:45.123456789").unwrap();
21793
21794 for year in [3000, 10_000, 300_000, i64::MAX / 400] {
21795 let out = ts.replace(Some(year), None, None, None, None, None, None, None);
21796 assert!(
21797 out.is_nat(),
21798 "replace(year={year}) is unrepresentable in i64 ns and must be \
21799 NaT, got nanos={:?} (year {:?}) — this is the silent wrap",
21800 out.nanos,
21801 out.year()
21802 );
21803 }
21804 for year in [-3000, -100_000, i64::MIN / 400] {
21805 let out = ts.replace(Some(year), None, None, None, None, None, None, None);
21806 assert!(out.is_nat(), "replace(year={year}) must be NaT");
21807 }
21808
21809 let in_range = ts.replace(
21814 Some(2262),
21815 Some(1),
21816 Some(1),
21817 Some(0),
21818 Some(0),
21819 Some(0),
21820 Some(0),
21821 Some(0),
21822 );
21823 assert!(
21824 !in_range.is_nat(),
21825 "2262-01-01 is representable and must survive"
21826 );
21827 assert_eq!(in_range.year(), Some(2262));
21828 assert!(
21829 ts.replace(
21830 Some(2263),
21831 Some(12),
21832 Some(31),
21833 Some(23),
21834 Some(59),
21835 Some(59),
21836 Some(999_999),
21837 Some(999)
21838 )
21839 .is_nat(),
21840 "end of 2263 exceeds the i64 ns axis and must be NaT"
21841 );
21842
21843 let unchanged = ts.replace(
21847 Some(1999),
21848 Some(6),
21849 Some(30),
21850 Some(12),
21851 Some(1),
21852 Some(2),
21853 Some(3),
21854 Some(4),
21855 );
21856 assert_eq!(unchanged.year(), Some(1999));
21857 assert_eq!(unchanged.month(), Some(6));
21858 assert_eq!(unchanged.day(), Some(30));
21859 assert_eq!(unchanged.hour(), Some(12));
21860 assert_eq!(unchanged.minute(), Some(1));
21861 assert_eq!(unchanged.second(), Some(2));
21862 assert_eq!(unchanged.microsecond(), Some(3));
21863 assert_eq!(unchanged.nanosecond(), Some(4));
21864 let tz = Timestamp::from_nanos_tz(ts.nanos, "UTC");
21865 assert_eq!(
21866 tz.replace(Some(1999), None, None, None, None, None, None, None)
21867 .tz
21868 .as_deref(),
21869 Some("UTC")
21870 );
21871 }
21872
21873 #[test]
21874 fn timestamp_component_accessors() {
21875 let ts = Timestamp::from_nanos(0);
21876 assert_eq!(ts.year(), Some(1970));
21877 assert_eq!(ts.month(), Some(1));
21878 assert_eq!(ts.day(), Some(1));
21879 assert_eq!(ts.hour(), Some(0));
21880 assert_eq!(ts.minute(), Some(0));
21881 assert_eq!(ts.second(), Some(0));
21882 assert_eq!(ts.microsecond(), Some(0));
21883 assert_eq!(ts.nanosecond(), Some(0));
21884
21885 let ts2 = Timestamp::from_nanos(
21886 Timedelta::NANOS_PER_DAY * 365
21887 + Timedelta::NANOS_PER_HOUR * 14
21888 + Timedelta::NANOS_PER_MIN * 30
21889 + Timedelta::NANOS_PER_SEC * 45
21890 + 123_456_789,
21891 );
21892 assert_eq!(ts2.year(), Some(1971));
21893 assert_eq!(ts2.month(), Some(1));
21894 assert_eq!(ts2.day(), Some(1));
21895 assert_eq!(ts2.hour(), Some(14));
21896 assert_eq!(ts2.minute(), Some(30));
21897 assert_eq!(ts2.second(), Some(45));
21898 assert_eq!(ts2.microsecond(), Some(123456));
21899 assert_eq!(ts2.nanosecond(), Some(789));
21900
21901 assert_eq!(Timestamp::nat().year(), None);
21902 assert_eq!(Timestamp::nat().month(), None);
21903 assert_eq!(Timestamp::nat().day(), None);
21904 }
21905
21906 #[test]
21907 fn timestamp_dayofweek_dayofyear_quarter() {
21908 let ts = Timestamp::from_nanos(0);
21909 assert_eq!(ts.dayofweek(), Some(3));
21910 assert_eq!(ts.weekday(), Some(3));
21911 assert_eq!(ts.dayofyear(), Some(1));
21912 assert_eq!(ts.quarter(), Some(1));
21913
21914 let ts2 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 90);
21915 assert_eq!(ts2.quarter(), Some(2));
21916
21917 let ts3 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 365);
21918 assert_eq!(ts3.dayofyear(), Some(1));
21919 assert_eq!(ts3.dayofweek(), Some(4));
21920
21921 assert_eq!(Timestamp::nat().dayofweek(), None);
21922 assert_eq!(Timestamp::nat().dayofyear(), None);
21923 assert_eq!(Timestamp::nat().quarter(), None);
21924 }
21925
21926 #[test]
21927 fn timestamp_is_boundary_methods() {
21928 let jan1 = Timestamp::from_nanos(0);
21929 assert_eq!(jan1.is_leap_year(), Some(false));
21930 assert_eq!(jan1.is_month_start(), Some(true));
21931 assert_eq!(jan1.is_month_end(), Some(false));
21932 assert_eq!(jan1.is_quarter_start(), Some(true));
21933 assert_eq!(jan1.is_quarter_end(), Some(false));
21934 assert_eq!(jan1.is_year_start(), Some(true));
21935 assert_eq!(jan1.is_year_end(), Some(false));
21936
21937 let dec31 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 364);
21938 assert_eq!(dec31.is_month_start(), Some(false));
21939 assert_eq!(dec31.is_month_end(), Some(true));
21940 assert_eq!(dec31.is_quarter_end(), Some(true));
21941 assert_eq!(dec31.is_year_end(), Some(true));
21942
21943 assert_eq!(Timestamp::nat().is_leap_year(), None);
21944 assert_eq!(Timestamp::nat().is_month_start(), None);
21945 }
21946
21947 #[test]
21948 fn timestamp_days_in_month() {
21949 let jan = Timestamp::from_nanos(0);
21950 assert_eq!(jan.days_in_month(), Some(31));
21951 assert_eq!(jan.daysinmonth(), Some(31));
21952
21953 let feb_non_leap = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 31);
21954 assert_eq!(feb_non_leap.days_in_month(), Some(28));
21955
21956 assert_eq!(Timestamp::nat().days_in_month(), None);
21957 }
21958
21959 #[test]
21960 fn timestamp_weekofyear() {
21961 let jan1 = Timestamp::from_nanos(0);
21962 assert_eq!(jan1.weekofyear(), Some(1));
21963 assert_eq!(jan1.week(), Some(1));
21964
21965 let jan8 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 7);
21966 assert_eq!(jan8.weekofyear(), Some(2));
21967
21968 assert_eq!(Timestamp::nat().weekofyear(), None);
21969 assert_eq!(Timestamp::nat().week(), None);
21970 }
21971
21972 #[test]
21973 fn timestamp_weekofyear_iso_53_week_boundaries() {
21974 fn week_of(date_days: i64) -> Option<i64> {
21977 Timestamp::from_nanos(date_days * Timedelta::NANOS_PER_DAY).weekofyear()
21978 }
21979 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)); }
21993
21994 #[test]
21995 fn iso_weeks_in_year_53_week_years() {
21996 use super::iso_weeks_in_year;
21997 for y in [2004, 2009, 2015, 2020, 2026] {
21999 assert_eq!(iso_weeks_in_year(y), 53, "{y} should have 53 ISO weeks");
22000 }
22001 for y in [2018, 2019, 2021, 2022, 2023, 2024] {
22002 assert_eq!(iso_weeks_in_year(y), 52, "{y} should have 52 ISO weeks");
22003 }
22004 }
22005
22006 #[test]
22007 fn timestamp_to_unit() {
22008 let ts = Timestamp::from_nanos(1_000_000_000);
22009 assert_eq!(ts.to_unit("ns"), Some(1_000_000_000));
22010 assert_eq!(ts.to_unit("us"), Some(1_000_000));
22011 assert_eq!(ts.to_unit("ms"), Some(1_000));
22012 assert_eq!(ts.to_unit("s"), Some(1));
22013 assert_eq!(ts.to_unit("invalid"), None);
22014
22015 assert_eq!(Timestamp::nat().to_unit("ns"), None);
22016 }
22017
22018 #[test]
22019 fn timestamp_toordinal() {
22020 let nanos_2026_01_01 = 19723_i64 * 24 * 60 * 60 * 1_000_000_000;
22023 let ts = Timestamp::from_nanos(nanos_2026_01_01);
22024 assert_eq!(ts.toordinal(), Some(738886));
22025
22026 assert_eq!(Timestamp::nat().toordinal(), None);
22028 }
22029
22030 #[test]
22031 fn timestamp_fromordinal() {
22032 let nanos_2026_01_01 = 19723_i64 * 24 * 60 * 60 * 1_000_000_000;
22035 let ts_orig = Timestamp::from_nanos(nanos_2026_01_01);
22036 let ordinal = ts_orig.toordinal().unwrap();
22037
22038 let ts = Timestamp::fromordinal(ordinal);
22040 assert_eq!(ts.year(), ts_orig.year());
22041 assert_eq!(ts.month(), ts_orig.month());
22042 assert_eq!(ts.day(), ts_orig.day());
22043
22044 let nat = Timestamp::fromordinal(0);
22046 assert!(nat.is_nat());
22047 }
22048
22049 #[test]
22050 fn timestamp_fromordinal_guards_nanosecond_overflow_ycvrd() {
22051 const EPOCH_ORDINAL: i64 = 719_163;
22052 let max_day_offset = i64::MAX / Timedelta::NANOS_PER_DAY;
22053 let max_valid_ordinal = EPOCH_ORDINAL + max_day_offset;
22054
22055 let max_valid = Timestamp::fromordinal(max_valid_ordinal);
22056 assert!(!max_valid.is_nat());
22057 assert_eq!(max_valid.nanos, max_day_offset * Timedelta::NANOS_PER_DAY);
22058
22059 assert!(Timestamp::fromordinal(max_valid_ordinal + 1).is_nat());
22060 assert!(Timestamp::fromordinal(i64::MAX).is_nat());
22061 }
22062
22063 #[test]
22064 fn timestamp_ordinal_matches_seeded_epoch_oracle_l2f0p() {
22065 const EPOCH_ORDINAL: i64 = 719_163;
22066 const DAY: i64 = Timedelta::NANOS_PER_DAY;
22067
22068 fn next(seed: &mut u64) -> u64 {
22069 *seed = seed
22070 .wrapping_mul(3202034522624059733)
22071 .wrapping_add(4354685564936845319);
22072 *seed
22073 }
22074
22075 fn assert_ordinal_case(case: usize, day_offset: i64, subday_nanos: i64) {
22076 let nanos = day_offset.saturating_mul(DAY).saturating_add(subday_nanos);
22077 let ts = Timestamp::from_nanos(nanos);
22078 let expected_day_offset = nanos.div_euclid(DAY);
22079 let expected_ordinal = EPOCH_ORDINAL + expected_day_offset;
22080
22081 assert_eq!(
22082 ts.toordinal(),
22083 Some(expected_ordinal),
22084 "case {case}: toordinal"
22085 );
22086
22087 let midnight = Timestamp::fromordinal(expected_ordinal);
22088 assert_eq!(
22089 midnight.nanos,
22090 expected_day_offset * DAY,
22091 "case {case}: fromordinal nanos"
22092 );
22093 assert_eq!(
22094 midnight.toordinal(),
22095 Some(expected_ordinal),
22096 "case {case}: fromordinal roundtrip"
22097 );
22098 }
22099
22100 assert_eq!(Timestamp::nat().toordinal(), None);
22101 assert!(Timestamp::fromordinal(0).is_nat());
22102 assert!(Timestamp::fromordinal(-1).is_nat());
22103
22104 assert_ordinal_case(usize::MAX, -1, DAY - 1);
22105 assert_ordinal_case(usize::MAX - 1, 0, -1);
22106 assert_ordinal_case(usize::MAX - 2, 19_723, 0);
22107
22108 let mut seed = 0x1f20_f0d1_0a11_0d1e_u64;
22109 for case in 0..260 {
22110 let day_offset = (next(&mut seed) % 40_001) as i64 - 10_000;
22111 let subday_nanos = match case % 7 {
22112 0 => 0,
22113 1 => DAY - 1,
22114 2 => -1,
22115 _ => (next(&mut seed) % (2 * DAY as u64 - 1)) as i64 - (DAY - 1),
22116 };
22117 assert_ordinal_case(case, day_offset, subday_nanos);
22118 }
22119 }
22120
22121 #[test]
22128 fn timestamp_parse_rejects_unrepresentable_years_94o1u() {
22129 for s in [
22130 "300000-01-01",
22131 "10000000-06-15T12:30:45",
22132 "999999999-01-01",
22133 "-300000-01-01",
22134 "-99999999-12-31T23:59:59",
22135 ] {
22136 let got = Timestamp::parse(s);
22137 assert!(
22138 got.is_err(),
22139 "parse({s:?}) is unrepresentable in i64 ns and must be Err, got {:?} \
22140 — this is the silent wrap",
22141 got.map(|ts| (ts.nanos, ts.year()))
22142 );
22143 }
22144
22145 let ok = Timestamp::parse("2262-01-01").expect("2262-01-01 is representable");
22148 assert_eq!(ok.year(), Some(2262));
22149 assert!(
22150 Timestamp::parse("2263-12-31T23:59:59").is_err(),
22151 "end of 2263 exceeds the i64 ns axis and must be Err"
22152 );
22153
22154 assert_eq!(Timestamp::parse("2024-01-15").unwrap().year(), Some(2024));
22158 assert_eq!(
22159 Timestamp::parse("2024-01-15T10:30:45").unwrap().hour(),
22160 Some(10)
22161 );
22162 assert_eq!(
22163 Timestamp::parse("2024-01-15 10:30:45").unwrap().minute(),
22164 Some(30)
22165 );
22166 assert_eq!(
22167 Timestamp::parse("2024-01-15T10:30:45.123456789")
22168 .unwrap()
22169 .nanosecond(),
22170 Some(789)
22171 );
22172 assert_eq!(
22173 Timestamp::parse("2024-01-15T00:00:00Z").unwrap().year(),
22174 Some(2024)
22175 );
22176 assert_eq!(Timestamp::parse("1900-01-01").unwrap().year(), Some(1900));
22178 }
22179
22180 #[test]
22181 fn timestamp_parse_iso8601_date_only() {
22182 let ts = Timestamp::parse("2024-01-15").unwrap();
22183 assert_eq!(ts.year(), Some(2024));
22184 assert_eq!(ts.month(), Some(1));
22185 assert_eq!(ts.day(), Some(15));
22186 assert_eq!(ts.hour(), Some(0));
22187 assert_eq!(ts.minute(), Some(0));
22188 assert_eq!(ts.second(), Some(0));
22189 }
22190
22191 #[test]
22192 fn timestamp_parse_iso8601_datetime() {
22193 let ts = Timestamp::parse("2024-01-15T10:30:45").unwrap();
22194 assert_eq!(ts.year(), Some(2024));
22195 assert_eq!(ts.month(), Some(1));
22196 assert_eq!(ts.day(), Some(15));
22197 assert_eq!(ts.hour(), Some(10));
22198 assert_eq!(ts.minute(), Some(30));
22199 assert_eq!(ts.second(), Some(45));
22200 }
22201
22202 #[test]
22203 fn timestamp_parse_space_separator() {
22204 let ts = Timestamp::parse("2024-01-15 10:30:45").unwrap();
22205 assert_eq!(ts.year(), Some(2024));
22206 assert_eq!(ts.hour(), Some(10));
22207 }
22208
22209 #[test]
22210 fn timestamp_parse_with_fractional_seconds() {
22211 let ts = Timestamp::parse("2024-01-15T10:30:45.123456789").unwrap();
22212 assert_eq!(ts.second(), Some(45));
22213 assert_eq!(ts.microsecond(), Some(123456));
22214 assert_eq!(ts.nanosecond(), Some(789));
22215 }
22216
22217 #[test]
22218 fn timestamp_parse_utc_timezone() {
22219 let ts = Timestamp::parse("2024-01-15T10:30:45Z").unwrap();
22220 assert_eq!(ts.tz, Some("UTC".to_string()));
22221 }
22222
22223 #[test]
22224 fn timestamp_parse_offset_timezone() {
22225 let ts = Timestamp::parse("2024-01-15T10:30:45+05:30").unwrap();
22226 assert_eq!(ts.tz, Some("+05:30".to_string()));
22227 let utc = |text: &str| Timestamp::parse(text).unwrap().nanos;
22230 assert_eq!(ts.nanos, utc("2024-01-15T05:00:45"));
22231
22232 let ts = Timestamp::parse("2024-01-15T10:30:45-05:30").unwrap();
22233 assert_eq!(ts.tz, Some("-05:30".to_string()));
22234 assert_eq!(ts.nanos, utc("2024-01-15T16:00:45"));
22235 assert_eq!(
22237 Timestamp::parse("2024-01-15T10:30:45Z").unwrap().nanos,
22238 utc("2024-01-15T10:30:45")
22239 );
22240 }
22241
22242 #[test]
22243 fn timestamp_parse_rejects_invalid_timezone_offsets_0v676() {
22244 assert!(Timestamp::parse("2024-01-15T10:30:45+bad").is_err());
22245 assert!(Timestamp::parse("2024-01-15T10:30:45+0500").is_err());
22246 assert!(Timestamp::parse("2024-01-15T10:30:45+24:00").is_err());
22247 assert!(Timestamp::parse("2024-01-15T10:30:45+05:60").is_err());
22248 assert!(Timestamp::parse("2024-01-15T10:30:45-25:00").is_err());
22249 }
22250
22251 #[test]
22252 fn timestamp_parse_nat() {
22253 let ts = Timestamp::parse("NaT").unwrap();
22254 assert!(ts.is_nat());
22255 let ts2 = Timestamp::parse("nat").unwrap();
22256 assert!(ts2.is_nat());
22257 }
22258
22259 #[test]
22260 fn timestamp_parse_invalid() {
22261 assert!(Timestamp::parse("not a date").is_err());
22262 assert!(Timestamp::parse("2024-13-01").is_err()); assert!(Timestamp::parse("2024-01-32").is_err()); }
22265
22266 #[test]
22267 fn timestamp_parse_rejects_invalid_fractional_seconds_87se2() {
22268 assert!(Timestamp::parse("2024-01-15T10:30:45.").is_err());
22269 assert!(Timestamp::parse("2024-01-15T10:30:45.abc").is_err());
22270 assert!(Timestamp::parse("2024-01-15T10:30:45.-1").is_err());
22271 assert!(Timestamp::parse("2024-01-15T10:30:45.123").is_err());
22272 assert!(Timestamp::parse("2024-01-15T10:30:45.123456789x").is_err());
22273
22274 let ts = Timestamp::parse("2024-01-15T10:30:45.123456789987").unwrap();
22275 assert_eq!(ts.second(), Some(45));
22276 assert_eq!(ts.microsecond(), Some(123456));
22277 assert_eq!(ts.nanosecond(), Some(789));
22278 }
22279
22280 #[test]
22281 #[ignore = "foreground profile-first A/B"]
22282 fn timestamp_parse_fraction_digit_fold_profile_pdiku() {
22283 use std::{hint::black_box, time::Instant};
22284
22285 const CALLS: usize = 131_072;
22286 const SAMPLES: usize = 12;
22287 type ParsedTime = Option<(u32, u32, u32, u64)>;
22288 const VALID: [&str; 16] = [
22289 "00:00:00.0",
22290 "01:02:03.1",
22291 "02:03:04.01",
22292 "03:04:05.001",
22293 "04:05:06.0001",
22294 "05:06:07.00001",
22295 "06:07:08.000001",
22296 "07:08:09.0000001",
22297 "08:09:10.00000001",
22298 "09:10:11.000000001",
22299 "10:11:12.123456789",
22300 "11:12:13.999999999",
22301 "12:13:14.123456789987",
22302 "13:14:15.000000000001",
22303 "14:15:16.101010101010",
22304 "23:59:59.987654321234",
22305 ];
22306
22307 #[inline(never)]
22308 fn former(s: &str) -> ParsedTime {
22309 let (time_str, frac_str) = match s.split_once('.') {
22310 Some((time, frac)) => (time, Some(frac)),
22311 None => (s, None),
22312 };
22313 let parts: Vec<&str> = time_str.split(':').collect();
22314 if parts.is_empty() || parts.len() > 3 {
22315 return None;
22316 }
22317 let hour: u32 = parts.first().and_then(|p| p.parse().ok())?;
22318 let minute: u32 = parts.get(1).and_then(|p| p.parse().ok()).unwrap_or(0);
22319 let second: u32 = parts.get(2).and_then(|p| p.parse().ok()).unwrap_or(0);
22320
22321 if hour > 23 || minute > 59 || second > 59 {
22322 return None;
22323 }
22324
22325 let nanos = match frac_str {
22326 None => 0,
22327 Some(frac) => {
22328 if frac.is_empty() || !frac.bytes().all(|b| b.is_ascii_digit()) {
22329 return None;
22330 }
22331 let truncated = &frac[..frac.len().min(9)];
22332 let padded = format!("{truncated:0<9}");
22333 padded.parse::<u64>().ok()?
22334 }
22335 };
22336
22337 Some((hour, minute, second, nanos))
22338 }
22339
22340 #[inline(never)]
22341 fn candidate(s: &str) -> ParsedTime {
22342 Timestamp::parse_time(s)
22343 }
22344
22345 fn elapsed(inputs: &[&str], parser: fn(&str) -> ParsedTime) -> u128 {
22346 let started = Instant::now();
22347 for input in black_box(inputs) {
22348 black_box(parser(black_box(*input)));
22349 }
22350 started.elapsed().as_nanos()
22351 }
22352
22353 fn percentile(samples: &[u128], percent: usize) -> u128 {
22354 let mut sorted = samples.to_vec();
22355 sorted.sort_unstable();
22356 let rank = (sorted.len() * percent).div_ceil(100).saturating_sub(1);
22357 sorted[rank]
22358 }
22359
22360 let invalid = [
22361 "",
22362 "24:00:00.1",
22363 "12:60:00.1",
22364 "12:00:60.1",
22365 "12:00:00.",
22366 "12:00:00.abc",
22367 "12:00:00.-1",
22368 "12:00:00.123",
22369 "12:00:00.123456789x",
22370 "12:00:00.1.2",
22371 "12:00:00:01.1",
22372 ];
22373 for input in VALID.iter().chain(invalid.iter()) {
22374 assert_eq!(candidate(input), former(input), "input={input:?}");
22375 }
22376
22377 let inputs = (0..CALLS)
22378 .map(|index| VALID[index % VALID.len()])
22379 .collect::<Vec<_>>();
22380 for _ in 0..2 {
22381 black_box(elapsed(&inputs, former));
22382 black_box(elapsed(&inputs, candidate));
22383 }
22384
22385 let mut former_ns = Vec::with_capacity(SAMPLES);
22386 let mut candidate_ns = Vec::with_capacity(SAMPLES);
22387 for sample in 0..SAMPLES {
22388 if sample.is_multiple_of(2) {
22389 former_ns.push(elapsed(&inputs, former));
22390 candidate_ns.push(elapsed(&inputs, candidate));
22391 } else {
22392 candidate_ns.push(elapsed(&inputs, candidate));
22393 former_ns.push(elapsed(&inputs, former));
22394 }
22395 }
22396
22397 let former_p50 = percentile(&former_ns, 50);
22398 let former_p95 = percentile(&former_ns, 95);
22399 let former_p99 = percentile(&former_ns, 99);
22400 let candidate_p50 = percentile(&candidate_ns, 50);
22401 let candidate_p95 = percentile(&candidate_ns, 95);
22402 let candidate_p99 = percentile(&candidate_ns, 99);
22403 println!(
22404 "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:?}",
22405 former_p50 as f64 / candidate_p50 as f64,
22406 former_p95 as f64 / candidate_p95 as f64,
22407 former_p99 as f64 / candidate_p99 as f64,
22408 );
22409 }
22410
22411 #[test]
22412 fn timestamp_parse_matches_seeded_iso_component_oracle_1u7a0() {
22413 fn next(seed: &mut u64) -> u64 {
22414 *seed = seed
22415 .wrapping_mul(3935559000370003845)
22416 .wrapping_add(2691343689449507681);
22417 *seed
22418 }
22419
22420 fn leap(year: i64) -> bool {
22421 (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
22422 }
22423
22424 fn month_len(year: i64, month: u32) -> u32 {
22425 match month {
22426 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
22427 4 | 6 | 9 | 11 => 30,
22428 2 if leap(year) => 29,
22429 2 => 28,
22430 _ => 0,
22431 }
22432 }
22433
22434 struct Components {
22435 year: i64,
22436 month: u32,
22437 day: u32,
22438 hour: u32,
22439 minute: u32,
22440 second: u32,
22441 nanos: u64,
22442 }
22443
22444 fn assert_components(case: usize, text: &str, expected: Components) {
22445 let ts = Timestamp::parse(text).expect("seeded valid timestamp");
22446 let Components {
22447 year,
22448 month,
22449 day,
22450 hour,
22451 minute,
22452 second,
22453 nanos,
22454 } = expected;
22455 assert_eq!(ts.year(), Some(year), "case {case}: year");
22456 assert_eq!(ts.month(), Some(month as i64), "case {case}: month");
22457 assert_eq!(ts.day(), Some(day as i64), "case {case}: day");
22458 assert_eq!(ts.hour(), Some(hour as i64), "case {case}: hour");
22459 assert_eq!(ts.minute(), Some(minute as i64), "case {case}: minute");
22460 assert_eq!(ts.second(), Some(second as i64), "case {case}: second");
22461 assert_eq!(
22462 ts.microsecond(),
22463 Some((nanos / 1000) as i64),
22464 "case {case}: microsecond"
22465 );
22466 assert_eq!(
22467 ts.nanosecond(),
22468 Some((nanos % 1000) as i64),
22469 "case {case}: nanosecond"
22470 );
22471 }
22472
22473 assert!(Timestamp::parse("NaT").expect("NaT parses").is_nat());
22474 assert!(
22475 Timestamp::parse("nAt")
22476 .expect("mixed-case NaT parses")
22477 .is_nat()
22478 );
22479 assert!(Timestamp::parse("1900-02-29").is_err());
22480 assert!(Timestamp::parse("2001-04-31").is_err());
22481 assert!(Timestamp::parse("2024-00-15").is_err());
22482
22483 assert_components(
22484 usize::MAX,
22485 "2000-02-29",
22486 Components {
22487 year: 2000,
22488 month: 2,
22489 day: 29,
22490 hour: 0,
22491 minute: 0,
22492 second: 0,
22493 nanos: 0,
22494 },
22495 );
22496 assert_components(
22497 usize::MAX - 1,
22498 "2024-02-29T23:59:59.000000001",
22499 Components {
22500 year: 2024,
22501 month: 2,
22502 day: 29,
22503 hour: 23,
22504 minute: 59,
22505 second: 59,
22506 nanos: 1,
22507 },
22508 );
22509
22510 let mut seed = 0x15e0_1d50_1f0a_cade_u64;
22511 for case in 0..260 {
22512 let year = 1900 + (next(&mut seed) % 201) as i64;
22513 let month = 1 + (next(&mut seed) % 12) as u32;
22514 let day = 1 + (next(&mut seed) % month_len(year, month) as u64) as u32;
22515 let hour = (next(&mut seed) % 24) as u32;
22516 let minute = (next(&mut seed) % 60) as u32;
22517 let second = (next(&mut seed) % 60) as u32;
22518 let nanos = next(&mut seed) % 1_000_000_000;
22519
22520 match case % 4 {
22521 0 => {
22522 let text = format!("{year:04}-{month:02}-{day:02}");
22523 assert_components(
22524 case,
22525 &text,
22526 Components {
22527 year,
22528 month,
22529 day,
22530 hour: 0,
22531 minute: 0,
22532 second: 0,
22533 nanos: 0,
22534 },
22535 );
22536 }
22537 1 => {
22538 let text =
22539 format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}");
22540 assert_components(
22541 case,
22542 &text,
22543 Components {
22544 year,
22545 month,
22546 day,
22547 hour,
22548 minute,
22549 second,
22550 nanos: 0,
22551 },
22552 );
22553 }
22554 2 => {
22555 let text =
22556 format!("{year:04}-{month:02}-{day:02} {hour:02}:{minute:02}:{second:02}");
22557 assert_components(
22558 case,
22559 &text,
22560 Components {
22561 year,
22562 month,
22563 day,
22564 hour,
22565 minute,
22566 second,
22567 nanos: 0,
22568 },
22569 );
22570 }
22571 _ => {
22572 let text = format!(
22573 "{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}.{nanos:09}"
22574 );
22575 assert_components(
22576 case,
22577 &text,
22578 Components {
22579 year,
22580 month,
22581 day,
22582 hour,
22583 minute,
22584 second,
22585 nanos,
22586 },
22587 );
22588 }
22589 }
22590 }
22591 }
22592
22593 #[test]
22594 fn period_parse_annual() {
22595 let p = Period::parse("2024").unwrap();
22596 assert_eq!(p.freq(), PeriodFreq::ANNUAL);
22597 assert_eq!(p.ordinal(), 2024 - 1970);
22598 }
22599
22600 #[test]
22601 fn period_parse_quarterly() {
22602 let p = Period::parse("2024Q1").unwrap();
22603 assert_eq!(p.freq(), PeriodFreq::QUARTERLY);
22604 assert_eq!(p.ordinal(), (2024 - 1970) * 4);
22605
22606 let p2 = Period::parse("2024q3").unwrap();
22607 assert_eq!(p2.freq(), PeriodFreq::QUARTERLY);
22608 assert_eq!(p2.ordinal(), (2024 - 1970) * 4 + 2);
22609 }
22610
22611 #[test]
22612 fn period_parse_monthly() {
22613 let p = Period::parse("2024-01").unwrap();
22614 assert_eq!(p.freq(), PeriodFreq::Monthly);
22615 assert_eq!(p.ordinal(), (2024 - 1970) * 12);
22616
22617 let p2 = Period::parse("2024-12").unwrap();
22618 assert_eq!(p2.freq(), PeriodFreq::Monthly);
22619 assert_eq!(p2.ordinal(), (2024 - 1970) * 12 + 11);
22620 }
22621
22622 #[test]
22623 fn period_parse_nat() {
22624 let p = Period::parse("NaT").unwrap();
22625 assert_eq!(p.ordinal(), i64::MIN);
22626 }
22627
22628 #[test]
22629 fn period_parse_invalid() {
22630 assert!(Period::parse("not a period").is_err());
22631 assert!(Period::parse("2024Q5").is_err()); assert!(Period::parse("2024-13").is_err()); }
22634
22635 #[test]
22636 fn interval_parse_basic() {
22637 let i = Interval::parse("[0, 1]").unwrap();
22638 assert_eq!(i.left, 0.0);
22639 assert_eq!(i.right, 1.0);
22640 assert_eq!(i.closed, IntervalClosed::Both);
22641
22642 let i2 = Interval::parse("(0, 1)").unwrap();
22643 assert_eq!(i2.left, 0.0);
22644 assert_eq!(i2.right, 1.0);
22645 assert_eq!(i2.closed, IntervalClosed::Neither);
22646
22647 let i3 = Interval::parse("[0, 1)").unwrap();
22648 assert_eq!(i3.closed, IntervalClosed::Left);
22649
22650 let i4 = Interval::parse("(0, 1]").unwrap();
22651 assert_eq!(i4.closed, IntervalClosed::Right);
22652 }
22653
22654 #[test]
22655 fn interval_parse_floats() {
22656 let i = Interval::parse("[-1.5, 2.5)").unwrap();
22657 assert_eq!(i.left, -1.5);
22658 assert_eq!(i.right, 2.5);
22659 assert_eq!(i.closed, IntervalClosed::Left);
22660 }
22661
22662 #[test]
22663 fn interval_parse_invalid() {
22664 assert!(Interval::parse("invalid").is_err());
22665 assert!(Interval::parse("[0]").is_err());
22666 assert!(Interval::parse("0, 1").is_err()); }
22668
22669 fn interval_parse_error_profile(s: &str) -> super::TypeError {
22670 super::TypeError::ValueNotParseable {
22671 value: s.to_string(),
22672 target: "Interval".to_string(),
22673 }
22674 }
22675
22676 #[inline(never)]
22677 fn interval_parse_former_profile(s: &str) -> Result<Interval, super::TypeError> {
22678 let s = std::hint::black_box(s).trim();
22679 if s.len() < 5 {
22680 return Err(interval_parse_error_profile(s));
22681 }
22682
22683 let first_char = s.chars().next().unwrap();
22684 let last_char = s.chars().last().unwrap();
22685 let left_closed = match first_char {
22686 '[' => true,
22687 '(' => false,
22688 _ => return Err(interval_parse_error_profile(s)),
22689 };
22690 let right_closed = match last_char {
22691 ']' => true,
22692 ')' => false,
22693 _ => return Err(interval_parse_error_profile(s)),
22694 };
22695 let closed = match (left_closed, right_closed) {
22696 (true, true) => IntervalClosed::Both,
22697 (true, false) => IntervalClosed::Left,
22698 (false, true) => IntervalClosed::Right,
22699 (false, false) => IntervalClosed::Neither,
22700 };
22701
22702 let inner = &s[1..s.len() - 1];
22703 let parts: Vec<&str> = inner.split(',').collect();
22704 if parts.len() != 2 {
22705 return Err(interval_parse_error_profile(s));
22706 }
22707 let left = parts[0]
22708 .trim()
22709 .parse()
22710 .map_err(|_| interval_parse_error_profile(s))?;
22711 let right = parts[1]
22712 .trim()
22713 .parse()
22714 .map_err(|_| interval_parse_error_profile(s))?;
22715 Ok(Interval::new(left, right, closed))
22716 }
22717
22718 #[inline(never)]
22719 fn interval_parse_split_once_profile(s: &str) -> Result<Interval, super::TypeError> {
22720 Interval::parse(std::hint::black_box(s))
22721 }
22722
22723 fn assert_interval_parse_profile_parity(s: &str) {
22724 match (
22725 interval_parse_former_profile(s),
22726 interval_parse_split_once_profile(s),
22727 ) {
22728 (Ok(former), Ok(candidate)) => {
22729 assert_eq!(former.left.to_bits(), candidate.left.to_bits(), "left: {s}");
22730 assert_eq!(
22731 former.right.to_bits(),
22732 candidate.right.to_bits(),
22733 "right: {s}"
22734 );
22735 assert_eq!(former.closed, candidate.closed, "closed: {s}");
22736 }
22737 (Err(former), Err(candidate)) => assert_eq!(former, candidate, "error: {s}"),
22738 (former, candidate) => assert_eq!(
22739 former.is_ok(),
22740 candidate.is_ok(),
22741 "parse result mismatch for {s}: {former:?} != {candidate:?}"
22742 ),
22743 }
22744 }
22745
22746 #[inline(never)]
22747 fn measure_interval_parser_profile(
22748 parser: fn(&str) -> Result<Interval, super::TypeError>,
22749 inputs: &[&str],
22750 rounds: usize,
22751 ) -> u128 {
22752 use std::{hint::black_box, time::Instant};
22753
22754 let started = Instant::now();
22755 let mut checksum = 0_u64;
22756 for _ in 0..rounds {
22757 for input in inputs {
22758 let parsed = parser(black_box(input)).expect("profile input must parse");
22759 let closed = match parsed.closed {
22760 IntervalClosed::Left => 1_u64,
22761 IntervalClosed::Right => 2,
22762 IntervalClosed::Both => 3,
22763 IntervalClosed::Neither => 4,
22764 };
22765 checksum = checksum
22766 .wrapping_add(parsed.left.to_bits().rotate_left(7))
22767 .wrapping_add(parsed.right.to_bits().rotate_right(11))
22768 .wrapping_add(closed);
22769 black_box(parsed);
22770 }
22771 }
22772 black_box(checksum);
22773 started.elapsed().as_nanos()
22774 }
22775
22776 #[test]
22777 #[ignore = "release-only attribution probe for br-frankenpandas-81jjv"]
22778 fn profile_interval_parse_endpoint_split_ab_81jjv() {
22779 const VALID: [&str; 8] = [
22780 "[0, 1]",
22781 "(-0.0, 0.0]",
22782 " [ -1.5e3 , 2.75E-4 ) ",
22783 "(NaN, -0]",
22784 "[-inf, inf)",
22785 "[9.25, -7.5]",
22786 "(4.9406564584124654e-324, 1.7976931348623157e308)",
22787 "[-42, 17.125)",
22788 ];
22789 const INVALID: [&str; 12] = [
22790 "invalid",
22791 "[0]",
22792 "0, 1",
22793 "[0 1]",
22794 "[0, 1, 2]",
22795 "[0, 1,]",
22796 "[0,,1]",
22797 "[, 1]",
22798 "[0, ]",
22799 "{0, 1}",
22800 "[0, 1}",
22801 " ⟦0, 1⟧ ",
22802 ];
22803 const ROUNDS: usize = 16_384;
22804 const SAMPLES: usize = 10;
22805
22806 for input in VALID.iter().chain(INVALID.iter()) {
22807 assert_interval_parse_profile_parity(input);
22808 }
22809 for _ in 0..2 {
22810 measure_interval_parser_profile(interval_parse_former_profile, &VALID, ROUNDS);
22811 measure_interval_parser_profile(interval_parse_split_once_profile, &VALID, ROUNDS);
22812 }
22813
22814 let mut former_ns = Vec::with_capacity(SAMPLES);
22815 let mut candidate_ns = Vec::with_capacity(SAMPLES);
22816 for sample in 0..SAMPLES {
22817 if sample % 2 == 0 {
22818 former_ns.push(measure_interval_parser_profile(
22819 interval_parse_former_profile,
22820 &VALID,
22821 ROUNDS,
22822 ));
22823 candidate_ns.push(measure_interval_parser_profile(
22824 interval_parse_split_once_profile,
22825 &VALID,
22826 ROUNDS,
22827 ));
22828 } else {
22829 candidate_ns.push(measure_interval_parser_profile(
22830 interval_parse_split_once_profile,
22831 &VALID,
22832 ROUNDS,
22833 ));
22834 former_ns.push(measure_interval_parser_profile(
22835 interval_parse_former_profile,
22836 &VALID,
22837 ROUNDS,
22838 ));
22839 }
22840 }
22841 former_ns.sort_unstable();
22842 candidate_ns.sort_unstable();
22843 let former_p50 = former_ns[SAMPLES / 2];
22844 let candidate_p50 = candidate_ns[SAMPLES / 2];
22845 let former_p95 = former_ns[SAMPLES - 1];
22846 let candidate_p95 = candidate_ns[SAMPLES - 1];
22847 println!("PROFILE_INTERVAL_PARSE_FORMER_NS={former_ns:?}");
22848 println!("PROFILE_INTERVAL_PARSE_CANDIDATE_NS={candidate_ns:?}");
22849 println!(
22850 "PROFILE_INTERVAL_PARSE_P50_RATIO={:.6}",
22851 former_p50 as f64 / candidate_p50 as f64
22852 );
22853 println!(
22854 "PROFILE_INTERVAL_PARSE_P95_RATIO={:.6}",
22855 former_p95 as f64 / candidate_p95 as f64
22856 );
22857 }
22858}
22859
22860#[cfg(test)]
22866mod float64_nullable_qkqfb {
22867 use super::{DType, NullKind, Scalar, cast_scalar, common_dtype};
22868
22869 #[test]
22880 fn the_two_float_flavours_have_different_missing_markers_qkqfb() {
22881 assert_eq!(
22882 Scalar::missing_for_dtype(DType::Float64Nullable),
22883 Scalar::Null(NullKind::Null),
22884 "the extension lane stores pd.NA"
22885 );
22886 assert_eq!(
22887 Scalar::missing_for_dtype(DType::Float64),
22888 Scalar::Null(NullKind::NaN),
22889 "the numpy lane stores a real NaN"
22890 );
22891 assert_ne!(
22894 Scalar::missing_for_dtype(DType::Float64Nullable),
22895 Scalar::missing_for_dtype(DType::Float64),
22896 );
22897 }
22898
22899 #[test]
22903 fn spelling_is_pandas_spelling_qkqfb() {
22904 assert_eq!(DType::Float64Nullable.name(), "Float64");
22905 assert_eq!(DType::Float64.name(), "float64");
22906 assert_ne!(DType::Float64Nullable.name(), DType::Float64.name());
22907 }
22908
22909 #[test]
22916 fn serde_round_trips_and_does_not_collide_with_numpy_float64_qkqfb() {
22917 let ext = serde_json::to_string(&DType::Float64Nullable).expect("serialize");
22918 let numpy = serde_json::to_string(&DType::Float64).expect("serialize");
22919 assert_eq!(ext, "\"Float64\"");
22920 assert_eq!(numpy, "\"float64\"");
22921 assert_ne!(ext, numpy);
22922
22923 assert_eq!(
22924 serde_json::from_str::<DType>(&ext).expect("deserialize"),
22925 DType::Float64Nullable
22926 );
22927 assert_eq!(
22928 serde_json::from_str::<DType>(&numpy).expect("deserialize"),
22929 DType::Float64
22930 );
22931 }
22932
22933 #[test]
22936 fn predicates_place_it_in_the_right_families_qkqfb() {
22937 assert!(DType::Float64Nullable.is_floating());
22938 assert!(DType::Float64Nullable.is_numeric());
22939 assert!(DType::Float64Nullable.is_any_real_numeric());
22940 assert!(DType::Float64Nullable.is_nullable());
22941 assert!(DType::Float64Nullable.is_extension());
22942 assert!(!DType::Float64Nullable.is_integer());
22945 assert!(!DType::Float64Nullable.is_signed_integer());
22946 assert!(!DType::Float64Nullable.is_bool());
22947 assert_eq!(DType::Float64Nullable.kind(), 'f');
22950 assert_eq!(DType::Float64Nullable.kind(), DType::Float64.kind());
22951 assert_eq!(DType::Float64Nullable.itemsize(), 8);
22952 }
22953
22954 #[test]
22957 fn nullable_pairing_is_an_involution_qkqfb() {
22958 assert_eq!(DType::Float64.to_nullable(), DType::Float64Nullable);
22959 assert_eq!(DType::Float64Nullable.to_non_nullable(), DType::Float64);
22960 assert_eq!(DType::Float64Nullable.to_nullable(), DType::Float64Nullable);
22962 assert_eq!(DType::Float64.to_non_nullable(), DType::Float64);
22963 assert_eq!(DType::Int64.to_nullable(), DType::Int64Nullable);
22965 assert_eq!(DType::Bool.to_nullable(), DType::BoolNullable);
22966 }
22967
22968 #[test]
22978 fn the_nullable_float_absorbs_every_numeric_flavour_qkqfb() {
22979 for other in [
22980 DType::Float64,
22981 DType::Int64,
22982 DType::Int64Nullable,
22983 DType::Bool,
22984 DType::BoolNullable,
22985 DType::Float64Nullable,
22986 ] {
22987 assert_eq!(
22988 common_dtype(DType::Float64Nullable, other.clone()),
22989 Ok(DType::Float64Nullable),
22990 "Float64Nullable + {other:?}"
22991 );
22992 assert_eq!(
22996 common_dtype(other.clone(), DType::Float64Nullable),
22997 Ok(DType::Float64Nullable),
22998 "{other:?} + Float64Nullable"
22999 );
23000 }
23001 assert_eq!(
23003 common_dtype(DType::Null, DType::Float64Nullable),
23004 Ok(DType::Float64Nullable)
23005 );
23006 }
23007
23008 #[test]
23017 fn casts_preserve_values_and_convert_only_the_marker_qkqfb() {
23018 let present = Scalar::Float64(1.5);
23019 assert_eq!(
23020 cast_scalar(&present, DType::Float64Nullable),
23021 Ok(Scalar::Float64(1.5))
23022 );
23023 assert_eq!(
23024 cast_scalar(&Scalar::Float64(1.5), DType::Float64),
23025 Ok(Scalar::Float64(1.5))
23026 );
23027 assert_eq!(
23029 cast_scalar(&Scalar::Int64(1), DType::Float64Nullable),
23030 Ok(Scalar::Float64(1.0))
23031 );
23032 assert_eq!(
23033 cast_scalar(&Scalar::Bool(true), DType::Float64Nullable),
23034 Ok(Scalar::Float64(1.0))
23035 );
23036
23037 assert_eq!(
23040 cast_scalar(&Scalar::Null(NullKind::NaN), DType::Float64Nullable),
23041 Ok(Scalar::Null(NullKind::Null)),
23042 "numpy NaN entering an extension lane becomes pd.NA"
23043 );
23044 assert_eq!(
23045 cast_scalar(&Scalar::Null(NullKind::Null), DType::Float64),
23046 Ok(Scalar::Null(NullKind::NaN)),
23047 "pd.NA entering a numpy lane becomes NaN"
23048 );
23049 }
23050
23051 #[test]
23061 fn int64nullable_plus_numpy_float_answers_the_nullable_float_qkqfb() {
23062 assert_eq!(
23063 common_dtype(DType::Int64Nullable, DType::Float64),
23064 Ok(DType::Float64Nullable)
23065 );
23066 assert_eq!(
23067 common_dtype(DType::Float64, DType::Int64Nullable),
23068 Ok(DType::Float64Nullable)
23069 );
23070 }
23071
23072 #[test]
23080 fn boolnullable_plus_numpy_float_answers_the_nullable_float_qkqfb() {
23081 assert_eq!(
23082 common_dtype(DType::BoolNullable, DType::Float64),
23083 Ok(DType::Float64Nullable)
23084 );
23085 assert_eq!(
23086 common_dtype(DType::Bool, DType::Float64),
23087 Ok(DType::Float64),
23088 "numpy bool + numpy float stays entirely on the numpy side"
23089 );
23090 }
23091
23092 #[test]
23103 fn the_nullable_float_flip_is_associative_on_its_witness_triple_qkqfb() {
23104 let (bn, i64n, f64d) = (DType::BoolNullable, DType::Int64, DType::Float64);
23105
23106 let left = common_dtype(
23107 common_dtype(bn.clone(), i64n.clone()).unwrap(),
23108 f64d.clone(),
23109 )
23110 .unwrap();
23111 let right = common_dtype(bn, common_dtype(i64n, f64d).unwrap()).unwrap();
23112
23113 assert_eq!(left, right, "promotion order must not change the result");
23114 assert_eq!(left, DType::Float64Nullable);
23115 }
23116}
23117
23118#[cfg(test)]
23123mod sparse_dtype_pandas_name_3gxc6 {
23124 use super::{DType, Scalar, SparseDType};
23125
23126 fn name(value_dtype: DType, fill: Scalar) -> String {
23127 SparseDType::new(value_dtype, fill)
23128 .expect("sparse descriptor")
23129 .pandas_name()
23130 }
23131
23132 #[test]
23135 fn int64_fill_zero_is_the_fixture_row() {
23136 assert_eq!(name(DType::Int64, Scalar::Int64(0)), "Sparse[int64, 0]");
23137 }
23138
23139 #[test]
23142 fn the_fill_value_is_actually_rendered() {
23143 assert_eq!(name(DType::Int64, Scalar::Int64(7)), "Sparse[int64, 7]");
23144 assert_ne!(
23145 name(DType::Int64, Scalar::Int64(0)),
23146 name(DType::Int64, Scalar::Int64(7)),
23147 "two different fills must not collapse to one name"
23148 );
23149 }
23150
23151 #[test]
23153 fn float64_nan_fill_is_lowercase_nan() {
23154 assert_eq!(
23155 name(DType::Float64, Scalar::Float64(f64::NAN)),
23156 "Sparse[float64, nan]"
23157 );
23158 }
23159
23160 #[test]
23163 fn float64_zero_fill_keeps_its_trailing_point_zero() {
23164 assert_eq!(
23165 name(DType::Float64, Scalar::Float64(0.0)),
23166 "Sparse[float64, 0.0]"
23167 );
23168 assert_ne!(
23169 name(DType::Float64, Scalar::Float64(0.0)),
23170 name(DType::Int64, Scalar::Int64(0)),
23171 "float64 and int64 zero fills are different dtypes"
23172 );
23173 }
23174
23175 #[test]
23177 fn bool_fill_uses_python_capitalisation() {
23178 assert_eq!(
23179 name(DType::Bool, Scalar::Bool(false)),
23180 "Sparse[bool, False]"
23181 );
23182 assert_eq!(name(DType::Bool, Scalar::Bool(true)), "Sparse[bool, True]");
23183 }
23184
23185 #[test]
23188 fn utf8_subtype_renders_as_object() {
23189 let rendered = name(DType::Utf8, Scalar::Null(crate::NullKind::NaN));
23190 assert!(
23191 rendered.starts_with("Sparse[object, "),
23192 "expected an object subtype, got {rendered}"
23193 );
23194 }
23195
23196 #[test]
23199 fn no_constructible_descriptor_renders_the_bare_name() {
23200 for (dtype, fill) in [
23201 (DType::Int64, Scalar::Int64(0)),
23202 (DType::Float64, Scalar::Float64(1.5)),
23203 (DType::Bool, Scalar::Bool(true)),
23204 (DType::Utf8, Scalar::Utf8("x".to_owned())),
23205 ] {
23206 let rendered = name(dtype.clone(), fill);
23207 assert_ne!(rendered, "Sparse", "bare name regressed for {dtype:?}");
23208 assert!(
23209 rendered.starts_with("Sparse[") && rendered.ends_with(']'),
23210 "malformed sparse name {rendered}"
23211 );
23212 }
23213 }
23214
23215 #[test]
23216 fn test_dtype_from_str_and_display() {
23217 use std::str::FromStr;
23218
23219 use crate::DType;
23220
23221 assert_eq!(DType::from_str("int64").unwrap(), DType::Int64);
23222 assert_eq!(DType::from_str("Int64").unwrap(), DType::Int64Nullable);
23223 assert_eq!(DType::from_str("float64").unwrap(), DType::Float64);
23224 assert_eq!(DType::from_str("Float64").unwrap(), DType::Float64Nullable);
23225 assert_eq!(DType::from_str("bool").unwrap(), DType::Bool);
23226 assert_eq!(DType::from_str("boolean").unwrap(), DType::BoolNullable);
23227 assert_eq!(DType::from_str("string").unwrap(), DType::Utf8);
23228 assert_eq!(DType::from_str("category").unwrap(), DType::Categorical);
23229 assert_eq!(
23230 DType::from_str("timedelta64[ns]").unwrap(),
23231 DType::Timedelta64
23232 );
23233 assert_eq!(
23234 DType::from_str("datetime64[ns]").unwrap(),
23235 DType::Datetime64 { tz: None }
23236 );
23237 assert_eq!(
23238 DType::from_str("datetime64[ns, UTC]").unwrap(),
23239 DType::Datetime64 {
23240 tz: Some("UTC".to_string())
23241 }
23242 );
23243 assert_eq!(DType::from_str("period").unwrap(), DType::Period);
23244 assert_eq!(DType::from_str("interval").unwrap(), DType::Interval);
23245 assert_eq!(DType::from_str("sparse").unwrap(), DType::Sparse);
23246
23247 assert_eq!(format!("{}", DType::Int64), "int64");
23248 assert_eq!(
23249 format!(
23250 "{}",
23251 DType::Datetime64 {
23252 tz: Some("UTC".to_string())
23253 }
23254 ),
23255 "datetime64[ns, UTC]"
23256 );
23257 }
23258
23259 #[test]
23260 fn test_api_types_inspection_and_infer_dtype() {
23261 use crate::{
23262 DType, Scalar,
23263 api::types::{
23264 infer_dtype, is_bool_dtype, is_categorical_dtype, is_datetime64_any_dtype,
23265 is_dtype_equal, is_extension_array_dtype, is_float_dtype, is_int64_dtype,
23266 is_integer_dtype, is_interval_dtype, is_numeric_dtype, is_object_dtype,
23267 is_period_dtype, is_scalar, is_signed_integer_dtype, is_sparse, is_string_dtype,
23268 is_timedelta64_dtype, is_unsigned_integer_dtype, pandas_dtype,
23269 },
23270 };
23271
23272 assert!(is_numeric_dtype(&DType::Int64));
23273 assert!(is_numeric_dtype(&DType::Float64));
23274 assert!(!is_numeric_dtype(&DType::Utf8));
23275 assert!(!is_numeric_dtype(&DType::Bool));
23276
23277 assert!(is_integer_dtype(&DType::Int64));
23278 assert!(is_integer_dtype(&DType::Int64Nullable));
23279 assert!(!is_integer_dtype(&DType::Float64));
23280
23281 assert!(is_int64_dtype(&DType::Int64));
23282 assert!(is_int64_dtype(&DType::Int64Nullable));
23283 assert!(!is_int64_dtype(&DType::Float64));
23284
23285 assert!(is_object_dtype(&DType::Utf8));
23286 assert!(!is_object_dtype(&DType::Int64));
23287
23288 assert!(is_dtype_equal(&DType::Int64, &DType::Int64));
23289 assert!(is_dtype_equal(&"int64", &DType::Int64));
23290 assert!(!is_dtype_equal(&DType::Int64, &DType::Float64));
23291
23292 assert!(is_signed_integer_dtype(&DType::Int64));
23293 assert!(!is_unsigned_integer_dtype(&DType::Int64));
23294
23295 assert!(is_float_dtype(&DType::Float64));
23296 assert!(is_bool_dtype(&DType::Bool));
23297 assert!(is_string_dtype(&DType::Utf8));
23298 assert!(is_datetime64_any_dtype(&DType::Datetime64 { tz: None }));
23299 assert!(is_timedelta64_dtype(&DType::Timedelta64));
23300 assert!(is_categorical_dtype(&DType::Categorical));
23301 assert!(is_period_dtype(&DType::Period));
23302 assert!(is_interval_dtype(&DType::Interval));
23303 assert!(is_sparse(&DType::Sparse));
23304 assert!(is_extension_array_dtype(&DType::Categorical));
23305 assert!(is_scalar(&Scalar::Int64(42)));
23306
23307 assert_eq!(pandas_dtype("float64").unwrap(), DType::Float64);
23308 assert!(pandas_dtype("invalid_dtype_xyz").is_err());
23309
23310 let ints = vec![Scalar::Int64(1), Scalar::Int64(2)];
23311 assert_eq!(infer_dtype(&ints, true), "integer");
23312
23313 let floats = vec![Scalar::Float64(1.0), Scalar::Float64(2.5)];
23314 assert_eq!(infer_dtype(&floats, true), "floating");
23315
23316 let bools = vec![Scalar::Bool(true), Scalar::Bool(false)];
23317 assert_eq!(infer_dtype(&bools, true), "boolean");
23318
23319 let strings = vec![Scalar::Utf8("a".to_string()), Scalar::Utf8("b".to_string())];
23320 assert_eq!(infer_dtype(&strings, true), "string");
23321
23322 let mixed = vec![Scalar::Int64(1), Scalar::Utf8("a".to_string())];
23323 assert_eq!(infer_dtype(&mixed, true), "mixed");
23324
23325 assert_eq!(infer_dtype(&[], true), "empty");
23326 }
23327
23328 #[test]
23329 fn test_na_nat_sentinels_and_eng_float_format() {
23330 use super::{
23331 NA, NAT, NaT, eng_float_format, get_eng_float_format, reset_eng_float_format,
23332 set_eng_float_format,
23333 };
23334
23335 assert!(NA.is_null());
23337 assert!(NAT.is_null());
23338 assert_eq!(NAT, NaT);
23339 assert_eq!(format!("{NA}"), "None");
23340 assert_eq!(format!("{NAT}"), "NaT");
23341
23342 assert_eq!(eng_float_format(1000.0, Some(3), false), "1.000E+03");
23344 assert_eq!(eng_float_format(0.005, Some(3), false), "5.000E-03");
23345 assert_eq!(eng_float_format(1234567.0, Some(3), false), "1.235E+06");
23346 assert_eq!(eng_float_format(-9876.54, Some(3), false), "-9.877E+03");
23347 assert_eq!(eng_float_format(0.0, Some(3), false), "0.000E+00");
23348
23349 assert_eq!(eng_float_format(1000.0, Some(3), true), "1.000k");
23351 assert_eq!(eng_float_format(0.005, Some(3), true), "5.000m");
23352 assert_eq!(eng_float_format(1234567.0, Some(3), true), "1.235M");
23353 assert_eq!(eng_float_format(-9876.54, Some(3), true), "-9.877k");
23354 assert_eq!(eng_float_format(0.0, Some(3), true), "0.000");
23355 assert_eq!(eng_float_format(1.5, Some(3), true), "1.500");
23356
23357 assert_eq!(eng_float_format(f64::NAN, Some(3), true), "NaN");
23359 assert_eq!(eng_float_format(f64::INFINITY, Some(3), true), "inf");
23360 assert_eq!(eng_float_format(f64::NEG_INFINITY, Some(3), true), "-inf");
23361
23362 reset_eng_float_format();
23364 assert_eq!(get_eng_float_format(), None);
23365 set_eng_float_format(4, true);
23366 assert_eq!(get_eng_float_format(), Some((4, true)));
23367 reset_eng_float_format();
23368 assert_eq!(get_eng_float_format(), None);
23369 }
23370
23371 #[test]
23372 fn test_options_system() {
23373 use super::{
23374 OptionError, OptionValue, describe_option, get_option, option_context, reset_option,
23375 set_option,
23376 };
23377
23378 reset_option(None).unwrap();
23380
23381 let max_rows = get_option("display.max_rows").unwrap();
23383 assert_eq!(max_rows.as_int(), Some(60));
23384 assert_eq!(max_rows, OptionValue::Int(60));
23385 assert!(!max_rows.is_none());
23386
23387 let min_rows = get_option("min_rows").unwrap();
23389 assert_eq!(min_rows.as_int(), Some(10));
23390
23391 set_option("display.max_rows", 100).unwrap();
23393 assert_eq!(get_option("display.max_rows").unwrap().as_int(), Some(100));
23394
23395 set_option("mode.sim_interactive", true).unwrap();
23396 assert_eq!(
23397 get_option("mode.sim_interactive").unwrap().as_bool(),
23398 Some(true)
23399 );
23400
23401 set_option("mode.chained_assignment", "raise").unwrap();
23402 assert_eq!(
23403 get_option("mode.chained_assignment").unwrap().as_str(),
23404 Some("raise")
23405 );
23406
23407 assert!(matches!(
23409 get_option("nonexistent.option"),
23410 Err(OptionError::NotFound { .. })
23411 ));
23412 assert!(matches!(
23413 get_option("display"),
23414 Err(OptionError::Ambiguous { .. })
23415 ));
23416
23417 let desc = describe_option(Some("max_rows")).unwrap();
23419 assert!(desc.contains("display.max_rows : [currently: 100]"));
23420
23421 let desc_all = describe_option(None).unwrap();
23422 assert!(desc_all.contains("display.width"));
23423 assert!(desc_all.contains("compute.use_bottleneck"));
23424
23425 {
23427 let _guard = option_context(&[
23428 ("display.max_rows", OptionValue::Int(999)),
23429 ("display.precision", OptionValue::Int(2)),
23430 ])
23431 .unwrap();
23432
23433 assert_eq!(get_option("display.max_rows").unwrap().as_int(), Some(999));
23434 assert_eq!(get_option("display.precision").unwrap().as_int(), Some(2));
23435 }
23436 assert_eq!(get_option("display.max_rows").unwrap().as_int(), Some(100));
23438 assert_eq!(get_option("display.precision").unwrap().as_int(), Some(6));
23439
23440 reset_option(Some("display.max_rows")).unwrap();
23442 assert_eq!(get_option("display.max_rows").unwrap().as_int(), Some(60));
23443
23444 reset_option(Some("all")).unwrap();
23445 assert_eq!(
23446 get_option("mode.chained_assignment").unwrap().as_str(),
23447 Some("warn")
23448 );
23449
23450 assert_eq!(
23452 get_option("mode.copy_on_write").unwrap().as_bool(),
23453 Some(false)
23454 );
23455 assert_eq!(
23456 get_option("mode.data_manager").unwrap().as_str(),
23457 Some("block")
23458 );
23459 assert_eq!(
23460 get_option("display.large_repr").unwrap().as_str(),
23461 Some("truncate")
23462 );
23463 assert_eq!(
23464 get_option("display.max_info_columns").unwrap().as_int(),
23465 Some(100)
23466 );
23467 assert_eq!(
23468 get_option("display.memory_usage").unwrap().as_bool(),
23469 Some(true)
23470 );
23471 assert_eq!(
23472 get_option("display.colheader_justify").unwrap().as_str(),
23473 Some("right")
23474 );
23475 assert!(get_option("display.chop_threshold").unwrap().is_none());
23476 assert_eq!(
23477 get_option("io.parquet.engine").unwrap().as_str(),
23478 Some("auto")
23479 );
23480 assert_eq!(
23481 get_option("plotting.backend").unwrap().as_str(),
23482 Some("matplotlib")
23483 );
23484 assert_eq!(
23485 get_option("plotting.matplotlib.register_converters")
23486 .unwrap()
23487 .as_bool(),
23488 Some(true)
23489 );
23490
23491 set_option("display.chop_threshold", ()).unwrap();
23493 assert!(get_option("display.chop_threshold").unwrap().is_none());
23494 }
23495
23496 #[test]
23497 fn test_scalar_typed_accessors() {
23498 use super::{Interval, IntervalClosed, Period, PeriodFreq, Scalar};
23499
23500 let s_i64 = Scalar::Int64(42);
23501 assert_eq!(s_i64.as_i64(), Some(42));
23502 assert_eq!(s_i64.as_int(), Some(42));
23503 assert_eq!(s_i64.as_f64(), None);
23504 assert_eq!(s_i64.as_float(), None);
23505 assert_eq!(s_i64.as_bool(), None);
23506 assert_eq!(s_i64.as_str(), None);
23507
23508 let s_f64 = Scalar::Float64(2.75);
23509 assert_eq!(s_f64.as_f64(), Some(2.75));
23510 assert_eq!(s_f64.as_float(), Some(2.75));
23511 assert_eq!(s_f64.as_i64(), None);
23512 assert_eq!(s_f64.as_int(), None);
23513
23514 let s_bool = Scalar::Bool(true);
23515 assert_eq!(s_bool.as_bool(), Some(true));
23516 assert_eq!(s_bool.as_int(), None);
23517
23518 let s_str = Scalar::Utf8("pandas".to_string());
23519 assert_eq!(s_str.as_str(), Some("pandas"));
23520 assert_eq!(s_str.as_bool(), None);
23521
23522 let s_dt = Scalar::Datetime64(1_000_000_000);
23523 assert_eq!(s_dt.as_datetime_nanos(), Some(1_000_000_000));
23524 assert_eq!(s_dt.as_str(), None);
23525
23526 let s_td = Scalar::Timedelta64(500_000);
23527 assert_eq!(s_td.as_timedelta_nanos(), Some(500_000));
23528 assert_eq!(s_td.as_int(), None);
23529
23530 let s_per = Scalar::Period(Period::new(2024, PeriodFreq::Daily));
23531 assert_eq!(s_per.as_period_ordinal(), Some(2024));
23532
23533 let s_iv = Scalar::Interval(Interval::new(0.0, 10.0, IntervalClosed::Both));
23534 assert_eq!(
23535 s_iv.as_interval(),
23536 Some(Interval::new(0.0, 10.0, IntervalClosed::Both))
23537 );
23538 }
23539
23540 #[test]
23541 fn test_api_submodules_and_types_inspectors() {
23542 use super::{
23543 DType, Scalar,
23544 api::{extensions, indexers, types},
23545 };
23546
23547 assert!(types::is_number(&Scalar::Int64(42)));
23549 assert!(types::is_number(&Scalar::Float64(42.5)));
23550 assert!(types::is_number(&Scalar::Bool(true)));
23551 assert!(!types::is_number(&Scalar::Utf8("pandas".into())));
23552
23553 assert!(types::is_bool(&Scalar::Bool(false)));
23554 assert!(!types::is_bool(&Scalar::Int64(0)));
23555
23556 assert!(types::is_integer(&Scalar::Int64(10)));
23557 assert!(!types::is_integer(&Scalar::Float64(10.0)));
23558
23559 assert!(types::is_float(&Scalar::Float64(10.0)));
23560 assert!(!types::is_float(&Scalar::Int64(10)));
23561
23562 assert!(types::is_float64_dtype(&DType::Float64));
23564 assert!(types::is_float64_dtype(&DType::Float64Nullable));
23565 assert!(!types::is_float64_dtype(&DType::Int64));
23566 assert!(!types::is_int32_dtype(&DType::Int64));
23567
23568 extensions::register_dataframe_accessor("geo");
23570 extensions::register_series_accessor("geo");
23571 extensions::register_index_accessor("geo");
23572
23573 let base = indexers::BaseIndexer::new(5, 1);
23575 assert_eq!(base.window_size, 5);
23576 assert_eq!(base.step, 1);
23577
23578 let fwd = indexers::FixedForwardWindowIndexer::new(3);
23579 assert_eq!(fwd.window_size, 3);
23580
23581 let var = indexers::VariableOffsetWindowIndexer::new(100);
23582 assert_eq!(var.index_offset, 100);
23583 }
23584
23585 #[test]
23586 fn test_extension_dtypes_and_parameterized_parsing() {
23587 use super::{
23588 AsDType, CategoricalDtype, DType, IntervalClosed, IntervalDtype, PeriodDtype, Scalar,
23589 SparseDType, api::types, pandas_dtype,
23590 };
23591
23592 let cat_default = CategoricalDtype::default();
23594 assert_eq!(cat_default.name(), "category");
23595 assert_eq!(cat_default.kind(), "O");
23596 assert!(!cat_default.ordered());
23597 assert_eq!(cat_default.categories(), None);
23598 assert_eq!(cat_default.as_dtype(), DType::Categorical);
23599 assert!(types::is_categorical_dtype(&cat_default));
23600 assert_eq!(
23601 cat_default.to_string(),
23602 "CategoricalDtype(categories=None, ordered=False)"
23603 );
23604
23605 let cat_custom =
23606 CategoricalDtype::new(Some(vec!["low".to_string(), "high".to_string()]), true);
23607 assert!(cat_custom.ordered());
23608 assert_eq!(
23609 cat_custom.categories(),
23610 Some(&["low".to_string(), "high".to_string()][..])
23611 );
23612 assert!(cat_custom.to_string().contains("ordered=True"));
23613
23614 let per_default = PeriodDtype::default();
23616 assert_eq!(per_default.freq(), "D");
23617 assert_eq!(per_default.name(), "period[D]");
23618 assert_eq!(per_default.kind(), "O");
23619 assert_eq!(per_default.as_dtype(), DType::Period);
23620 assert!(types::is_period_dtype(&per_default));
23621 assert_eq!(per_default.to_string(), "period[D]");
23622
23623 let per_custom = PeriodDtype::new("M");
23624 assert_eq!(per_custom.freq(), "M");
23625 assert_eq!(per_custom.to_string(), "period[M]");
23626
23627 let int_default = IntervalDtype::default();
23629 assert_eq!(*int_default.subtype(), DType::Float64);
23630 assert_eq!(int_default.closed(), Some(IntervalClosed::Right));
23631 assert_eq!(int_default.name(), "interval");
23632 assert_eq!(int_default.kind(), "O");
23633 assert_eq!(int_default.as_dtype(), DType::Interval);
23634 assert!(types::is_interval_dtype(&int_default));
23635 assert_eq!(int_default.to_string(), "interval[float64, right]");
23636
23637 let int_custom = IntervalDtype::new(DType::Int64, Some(IntervalClosed::Both));
23638 assert_eq!(*int_custom.subtype(), DType::Int64);
23639 assert_eq!(int_custom.closed(), Some(IntervalClosed::Both));
23640 assert_eq!(int_custom.to_string(), "interval[int64, both]");
23641
23642 let sp = SparseDType::new(DType::Float64, Scalar::Float64(0.0)).unwrap();
23644 assert_eq!(sp.as_dtype(), DType::Sparse);
23645 assert!(types::is_sparse(&sp));
23646
23647 assert_eq!(pandas_dtype("period[D]").unwrap(), DType::Period);
23649 assert_eq!(pandas_dtype("Period[M]").unwrap(), DType::Period);
23650 assert_eq!(pandas_dtype("interval[float64]").unwrap(), DType::Interval);
23651 assert_eq!(pandas_dtype("Interval[int64]").unwrap(), DType::Interval);
23652 assert_eq!(pandas_dtype("sparse[float64]").unwrap(), DType::Sparse);
23653 assert_eq!(pandas_dtype("Sparse[int64, 0]").unwrap(), DType::Sparse);
23654 }
23655}
23656
23657#[cfg(test)]
23660mod numeric_width_fvsao23 {
23661 use super::{DType, NumericWidth, NumpyNumeric, numpy_pairwise_sum};
23662
23663 #[test]
23664 fn float32_sum_is_numpys_pairwise_sum_bit_for_bit() {
23665 let cases: [(usize, u32); 5] = [
23669 (5, 1_083_829_126),
23670 (64, 1_136_679_190),
23671 (129, 1_145_981_108),
23672 (1000, 1_170_926_592),
23673 (4097, 1_188_011_795),
23674 ];
23675 for (n, bits) in cases {
23676 #[allow(clippy::cast_precision_loss)] let values: Vec<f32> = (0..n)
23678 .map(|k| ((k * 37) % 1000) as f32 * 0.013_f32)
23679 .collect();
23680 assert_eq!(numpy_pairwise_sum(&values).to_bits(), bits, "n={n}");
23681 if n < 100 {
23682 #[allow(clippy::cast_possible_truncation)]
23683 let rounded_once = values.iter().map(|&v| f64::from(v)).sum::<f64>() as f32;
23684 assert_ne!(rounded_once.to_bits(), bits, "n={n}");
23685 }
23686 }
23687 assert_eq!(numpy_pairwise_sum::<f32>(&[]), 0.0);
23688 }
23689
23690 #[test]
23691 fn names_parse_and_round_trip() {
23692 for width in NumericWidth::ALL {
23693 for nullable in [false, true] {
23694 assert_eq!(
23695 NumericWidth::parse(width.name(nullable)),
23696 Some((width, nullable))
23697 );
23698 }
23699 }
23700 for (name, expected) in [
23701 ("<i4", (NumericWidth::Int32, false)),
23702 ("f4", (NumericWidth::Float32, false)),
23703 ("UInt8Dtype", (NumericWidth::UInt8, true)),
23704 ] {
23705 assert_eq!(NumericWidth::parse(name), Some(expected), "{name}");
23706 }
23707 for name in ["int64", "Int64", "float64", "i8", "f8", "int", "float"] {
23709 assert_eq!(NumericWidth::parse(name), None, "{name}");
23710 }
23711 }
23712
23713 #[test]
23714 fn wrapping_is_numpys_modular_cast_not_saturation() {
23715 assert_eq!(NumericWidth::Int8.wrap_int(300), Some(44));
23717 assert_eq!(NumericWidth::UInt8.wrap_int(-5), Some(251));
23719 assert_eq!(NumericWidth::UInt16.wrap_int(-5), Some(65531));
23720 assert_eq!(NumericWidth::UInt32.wrap_int(-5), Some(4_294_967_291));
23721 assert_eq!(NumericWidth::Int8.wrap_int(200), Some(-56));
23723 assert_eq!(
23724 NumericWidth::Int32.wrap_int(i64::from(i32::MAX) + 1),
23725 Some(i64::from(i32::MIN))
23726 );
23727 let product = 50_000_i64.wrapping_pow(5);
23729 assert_eq!(
23730 NumericWidth::Int32.wrap_int(product),
23731 Some(i64::from(50_000_i32.wrapping_pow(5)))
23732 );
23733 assert_eq!(NumericWidth::UInt64.wrap_int(-1), None);
23735 assert_eq!(NumericWidth::UInt64.wrap_int(7), Some(7));
23736 assert_eq!(NumericWidth::Float32.wrap_int(1), None);
23737 assert!(NumericWidth::Int8.holds_int(-128) && !NumericWidth::Int8.holds_int(128));
23738 }
23739
23740 #[test]
23741 fn float32_rounding_is_to_nearest_not_truncation() {
23742 assert_eq!(NumericWidth::round_f32(0.1), 0.100_000_001_490_116_12);
23744 let sum =
23747 NumericWidth::round_f32(NumericWidth::round_f32(0.1) + NumericWidth::round_f32(0.2));
23748 assert_eq!(sum, 0.300_000_011_920_928_96);
23749 assert_eq!(NumericWidth::round_f32(1.0 + 2f64.powi(-24)), 1.0);
23752 let above_tie = 1.0 + 3.0 * 2f64.powi(-25);
23753 assert_eq!(NumericWidth::round_f32(above_tie), 1.0 + 2f64.powi(-23));
23754 assert!(NumericWidth::round_f32(f64::NAN).is_nan());
23755 assert_eq!(NumericWidth::round_f32(1e300), f64::INFINITY);
23756 }
23757
23758 #[test]
23759 fn result_type_matches_numpy_promotion() {
23760 use NumpyNumeric::{Bool, Float, Int, UInt};
23761 let cases = [
23762 (Int(32), Int(64), Int(64)), (Int(8), UInt(8), Int(16)), (Int(16), UInt(8), Int(16)),
23765 (Int(8), UInt(16), Int(32)),
23766 (Int(32), UInt(32), Int(64)),
23767 (Int(64), UInt(64), Float(64)), (UInt(8), UInt(32), UInt(32)),
23769 (Float(32), Int(8), Float(32)), (Float(32), UInt(16), Float(32)),
23771 (Float(32), Int(32), Float(64)), (Float(32), Float(64), Float(64)),
23773 (Bool, Int(8), Int(8)),
23774 (Bool, Float(32), Float(32)),
23775 ];
23776 for (a, b, expected) in cases {
23777 assert_eq!(a.result_type(b), expected, "{a:?} {b:?}");
23778 assert_eq!(b.result_type(a), expected, "{b:?} {a:?}");
23779 }
23780 assert_eq!(Int(32).with_python_int(), Int(32));
23783 assert_eq!(Int(32).with_python_float(), Float(64));
23784 assert_eq!(Float(32).with_python_float(), Float(32));
23785 assert_eq!(Bool.with_python_int(), Int(64));
23786 }
23787
23788 #[test]
23789 fn columns_map_to_numpy_dtypes() {
23790 let cases = [
23791 (DType::Int64, None, Some(NumpyNumeric::Int(64))),
23792 (
23793 DType::Int64Nullable,
23794 Some(NumericWidth::UInt8),
23795 Some(NumpyNumeric::UInt(8)),
23796 ),
23797 (
23798 DType::Float64,
23799 Some(NumericWidth::Float32),
23800 Some(NumpyNumeric::Float(32)),
23801 ),
23802 (DType::Float64, Some(NumericWidth::Int8), None),
23804 (DType::Utf8, None, None),
23805 ];
23806 for (dtype, width, expected) in cases {
23807 assert_eq!(NumpyNumeric::of(&dtype, width), expected, "{dtype:?}");
23808 }
23809 for width in NumericWidth::ALL {
23810 assert_eq!(NumpyNumeric::of_width(width).width(), Some(width));
23811 assert!(width.fits_storage(&width.storage(false)));
23812 assert!(width.fits_storage(&width.storage(true)));
23813 }
23814 assert_eq!(NumpyNumeric::Int(64).width(), None);
23815 }
23816
23817 #[test]
23818 fn downcast_and_category_code_widths() {
23819 let int32_max_plus_one = i64::from(i32::MAX) + 1;
23822 let signed = [
23823 ((1, 2), Some(NumericWidth::Int8)),
23824 ((1, 300), Some(NumericWidth::Int16)),
23825 ((0, int32_max_plus_one), None),
23826 ];
23827 for ((low, high), expected) in signed {
23828 assert_eq!(NumericWidth::smallest_signed(low, high), expected);
23829 }
23830 let unsigned = [((1, 300), Some(NumericWidth::UInt16)), ((-1, 3), None)];
23831 for ((low, high), expected) in unsigned {
23832 assert_eq!(NumericWidth::smallest_unsigned(low, high), expected);
23833 }
23834 for (categories, expected) in [
23836 (2, NumericWidth::Int8),
23837 (126, NumericWidth::Int8),
23838 (127, NumericWidth::Int16),
23839 (200, NumericWidth::Int16),
23840 ] {
23841 assert_eq!(NumericWidth::for_category_codes(categories), Some(expected));
23842 }
23843 assert_eq!(NumericWidth::itemsize(NumericWidth::Int8), 1);
23844 assert_eq!(NumericWidth::Float32.itemsize(), 4);
23845 }
23846}
23847
23848#[cfg(test)]
23853mod pandas_reductions_9iim6 {
23854 use super::{MissingLayout, PandasReductions, ReductionValues};
23855
23856 #[allow(clippy::cast_precision_loss)] fn floats(n: usize) -> (Vec<f64>, Vec<u64>) {
23860 let mut present = vec![0_u64; n.div_ceil(64)];
23861 let values = (0..n)
23862 .map(|k| {
23863 if k % 11 != 3 {
23864 present[k / 64] |= 1 << (k % 64);
23865 }
23866 let base = ((k * 7919 + 13) % 100_003) as f64 / 7.0 - 7000.0;
23867 if k % 5 == 0 { base * 1e6 } else { base }
23868 })
23869 .collect();
23870 (values, present)
23871 }
23872
23873 fn ints(n: usize) -> Vec<i64> {
23875 (0..n)
23876 .map(|k| i64::try_from((k * 7919 + 13) % 100_003).unwrap() * 3_000_000_007)
23877 .collect()
23878 }
23879
23880 fn assert_bits(got: &[f64], expected: &[u64], case: &str) {
23881 let got: Vec<u64> = got.iter().map(|value| value.to_bits()).collect();
23882 assert_eq!(got, expected, "{case}");
23883 }
23884
23885 #[test]
23886 fn numpy_float64_with_nan_matches_pandas_bits() {
23887 let cases: [(usize, [u64; 7]); 7] = [
23889 (
23890 7,
23891 [
23892 0xc1ff_1185_2dcb_6db6,
23893 0xc1d4_b658_c932_4924,
23894 0x43db_301d_4a8d_87a3,
23895 0x41e4_db58_e2f1_458e,
23896 0x41d1_078f_09d3_9c5c,
23897 0xc002_1f47_ceae_1b43,
23898 0x4014_c8bc_93df_56e6,
23899 ],
23900 ),
23901 (
23902 8,
23903 [
23904 0xc1ff_1184_f43d_b6da,
23905 0xc1d1_c0de_426c_687d,
23906 0x43d7_9d3c_ecd2_da2b,
23907 0x41e3_7012_7d6c_71a5,
23908 0x41cd_631d_3379_9929,
23909 0xc003_b196_82f9_28dc,
23910 0x4018_9de2_eba9_5ecc,
23911 ],
23912 ),
23913 (
23914 127,
23915 [
23916 0x4200_324e_3389_2490,
23917 0x4192_0704_ad1e_360d,
23918 0x43c9_4a6b_3390_577d,
23919 0x41dc_72bf_d6fa_9808,
23920 0x41a5_38f5_8417_ae1e,
23921 0x3fd0_b6bf_045c_e4d5,
23922 0x4017_1585_bf13_21c4,
23923 ],
23924 ),
23925 (
23926 128,
23927 [
23928 0x4200_324d_7236_db6e,
23929 0x4191_df3a_f99d_a2ae,
23930 0x43c9_1234_ffb7_4a93,
23931 0x41dc_5310_c97c_292c,
23932 0x41a5_09f4_cfcf_9206,
23933 0x3fd0_d9df_0d68_00b0,
23934 0x4017_61b6_5653_ae82,
23935 ],
23936 ),
23937 (
23938 129,
23939 [
23940 0x4200_324c_d43e_db71,
23941 0x4191_b81f_8a1d_61da,
23942 0x43c8_daf6_85d3_386f,
23943 0x41dc_33ca_af49_8c24,
23944 0x41a4_dbc2_8609_a567,
23945 0x3fd0_fcc5_39d9_6901,
23946 0x4017_ade4_7855_7c25,
23947 ],
23948 ),
23949 (
23950 1000,
23951 [
23952 0x421a_d4f6_8061_248e,
23953 0x417e_39f9_3e1a_a248,
23954 0x43c7_9481_cba1_263b,
23955 0x41db_7825_28c0_37cc,
23956 0x418d_27ba_a0ea_2f9a,
23957 0x3fc8_e53a_e277_3d7f,
23958 0x4018_3c97_3603_dfd0,
23959 ],
23960 ),
23961 (
23962 100_000,
23963 [
23964 0x4283_088c_316e_46dc,
23965 0x417b_7135_0c27_1185,
23966 0x43c7_a0de_3b8e_ea34,
23967 0x41db_7f57_6673_8d6b,
23968 0x4157_58cc_33fd_4ae6,
23969 0x3fc7_f1cf_b14a_14c8,
23970 0x4018_06b5_f26a_c384,
23971 ],
23972 ),
23973 ];
23974 let all = |r: &PandasReductions<'_>| {
23975 [
23976 r.sum(),
23977 r.mean(),
23978 r.var(1),
23979 r.std(1),
23980 r.sem(1),
23981 r.skew(),
23982 r.kurt(),
23983 ]
23984 };
23985 for (n, expected) in cases {
23986 let (values, present) = floats(n);
23987 let r = PandasReductions::new(
23988 ReductionValues::Float(&values),
23989 Some(&present),
23990 MissingLayout::Numpy,
23991 );
23992 assert_bits(&all(&r), &expected, &format!("float64 n={n}"));
23993 let with_nan: Vec<f64> = values
23996 .iter()
23997 .enumerate()
23998 .map(|(k, &value)| if k % 11 == 3 { f64::NAN } else { value })
23999 .collect();
24000 let r = PandasReductions::numpy_nan_missing(ReductionValues::Float(&with_nan));
24001 assert_bits(&all(&r), &expected, &format!("float64 NaN n={n}"));
24002 let (head, tail) = with_nan.split_at(n / 3);
24003 let chunks = [head, tail];
24004 let r = PandasReductions::numpy_nan_missing(ReductionValues::FloatChunks(&chunks));
24005 assert_bits(&all(&r), &expected, &format!("float64 NaN chunks n={n}"));
24006 }
24007 let (values, present) = floats(100_000);
24009 let left_fold: f64 = values
24010 .iter()
24011 .enumerate()
24012 .filter(|&(k, _)| present[k / 64] >> (k % 64) & 1 == 1)
24013 .map(|(_, value)| value)
24014 .sum();
24015 assert_ne!(left_fold.to_bits(), 0x4283_088c_316e_46dc);
24016 }
24017
24018 #[test]
24019 fn numpy_int64_mean_sums_through_the_cast_buffer() {
24020 let cases: [(usize, [u64; 5]); 3] = [
24022 (
24023 129,
24024 [
24025 0x42e0_dda2_9987_3f9e,
24026 0x45b9_0e2a_887d_aeda,
24027 0x429c_34a1_c273_372f,
24028 0x3f95_9e9d_c69e_ec88,
24029 0xbff3_844b_ba13_eac1,
24030 ],
24031 ),
24032 (
24033 8193,
24034 [
24035 0x42e1_0d5b_e407_5aa7,
24036 0x45b8_3bf5_04f5_f2fc,
24037 0x426b_d893_c5c9_85b1,
24038 0x3f42_7452_ff15_86c7,
24039 0xbff3_318c_611b_b59c,
24040 ],
24041 ),
24042 (
24043 20_000,
24044 [
24045 0x42e1_0d17_ebf8_272d,
24046 0x45b8_3c24_c921_82b6,
24047 0x4261_d2a2_f139_68e2,
24048 0x3f31_a21c_d4bb_ff52,
24049 0xbff3_328c_4edc_26ee,
24050 ],
24051 ),
24052 ];
24053 for (n, expected) in cases {
24054 let values = ints(n);
24055 let r =
24056 PandasReductions::new(ReductionValues::Int(&values), None, MissingLayout::Numpy);
24057 let got = [r.mean(), r.var(1), r.sem(1), r.skew(), r.kurt()];
24058 assert_bits(&got, &expected, &format!("int64 n={n}"));
24059 let (head, tail) = values.split_at(n / 3);
24061 let (middle, rest) = tail.split_at(1);
24062 let chunks = [head, middle, &[][..], rest];
24063 let chunked = PandasReductions::new(
24064 ReductionValues::IntChunks(&chunks),
24065 None,
24066 MissingLayout::Numpy,
24067 );
24068 let got = [
24069 chunked.mean(),
24070 chunked.var(1),
24071 chunked.sem(1),
24072 chunked.skew(),
24073 chunked.kurt(),
24074 ];
24075 assert_bits(&got, &expected, &format!("int64 chunks n={n}"));
24076 }
24077 }
24078
24079 #[test]
24080 fn masked_columns_add_runs_of_present_values() {
24081 let cases: [(usize, [u64; 4]); 3] = [
24085 (
24086 129,
24087 [
24088 0x4200_324c_d43e_db6e,
24089 0x4191_b81f_8a1d_61d6,
24090 0x43c8_daf6_85d3_3872,
24091 0x41a4_dbc2_8609_a567,
24092 ],
24093 ),
24094 (
24095 1000,
24096 [
24097 0x421a_d4f6_8061_2492,
24098 0x417e_39f9_3e1a_a24c,
24099 0x43c7_9481_cba1_263a,
24100 0x418d_27ba_a0ea_2f9a,
24101 ],
24102 ),
24103 (
24104 100_000,
24105 [
24106 0x4283_088c_316e_46de,
24107 0x417b_7135_0c27_1188,
24108 0x43c7_a0de_3b8e_ea37,
24109 0x4157_58cc_33fd_4ae6,
24110 ],
24111 ),
24112 ];
24113 for (n, expected) in cases {
24114 let (values, present) = floats(n);
24115 let r = PandasReductions::new(
24116 ReductionValues::Float(&values),
24117 Some(&present),
24118 MissingLayout::Masked,
24119 );
24120 assert_bits(
24121 &[r.sum(), r.mean(), r.var(1), r.sem(1)],
24122 &expected,
24123 &format!("Float64 n={n}"),
24124 );
24125 let (head, tail) = values.split_at(n / 2 + 1);
24126 let chunks = [head, tail];
24127 let chunked = PandasReductions::new(
24128 ReductionValues::FloatChunks(&chunks),
24129 Some(&present),
24130 MissingLayout::Masked,
24131 );
24132 let got = [
24133 chunked.sum(),
24134 chunked.mean(),
24135 chunked.var(1),
24136 chunked.sem(1),
24137 ];
24138 assert_bits(&got, &expected, &format!("Float64 chunks n={n}"));
24139 }
24140 for (n, expected) in [
24143 (8193, [0x42e1_0f35_29c2_807b_u64, 0x45b8_39ed_8746_bdcc]),
24144 (20_000, [0x42e1_0cf2_cc56_752a, 0x45b8_3c63_72fc_fad5]),
24145 ] {
24146 let values = ints(n);
24147 let mut present = vec![0_u64; n.div_ceil(64)];
24148 for k in (0..n).filter(|k| k % 997 != 5) {
24149 present[k / 64] |= 1 << (k % 64);
24150 }
24151 let r = PandasReductions::new(
24152 ReductionValues::Int(&values),
24153 Some(&present),
24154 MissingLayout::Masked,
24155 );
24156 assert_bits(&[r.mean(), r.var(1)], &expected, &format!("Int64 n={n}"));
24157 }
24158 }
24159
24160 #[test]
24161 fn edge_cases_match_pandas() {
24162 let reductions = |values: &[f64], present: Option<&[u64]>| {
24163 let r = PandasReductions::new(
24164 ReductionValues::Float(values),
24165 present,
24166 MissingLayout::Numpy,
24167 );
24168 [r.sum(), r.mean(), r.var(1), r.sem(1), r.skew(), r.kurt()]
24169 };
24170 let constant = reductions(&[1.5; 10], None);
24173 assert_eq!(constant, [15.0, 1.5, 0.0, 0.0, 0.0, 0.0]);
24174 assert!(reductions(&[2.0; 3], None)[5].is_nan());
24175 assert!(reductions(&[1.0, 2.0], None)[4].is_nan());
24177 assert_eq!(
24178 reductions(&[1.0, 2.0, 4.0], None)[4],
24179 0.935_219_529_582_823_7
24180 );
24181 let empty = reductions(&[], None);
24183 assert_eq!(empty[0], 0.0);
24184 assert!(empty[1..].iter().all(|value| value.is_nan()));
24185 let all_missing = reductions(&[3.0; 5], Some(&[0]));
24186 assert_eq!(all_missing[0], 0.0);
24187 assert!(all_missing[1].is_nan());
24188 assert_eq!(
24190 reductions(&[-0.0; 10], None)[0].to_bits(),
24191 0.0_f64.to_bits()
24192 );
24193 let inf = reductions(&[1.0, f64::INFINITY, 2.0, 5.0], None);
24195 assert_eq!(inf[0], f64::INFINITY);
24196 assert!(inf[2..].iter().all(|value| value.is_nan()));
24197 }
24198
24199 #[test]
24200 fn int64_mean_skipping_is_the_filled_mean_vk7y9() {
24201 const NAT: i64 = i64::MIN;
24205 let nanos: Vec<i64> = (0..20_000_i64)
24206 .map(|k| {
24207 if k % 13 == 5 {
24208 NAT
24209 } else {
24210 1_577_836_800_000_000_000 + k * 3_600_000_000_123
24211 }
24212 })
24213 .collect();
24214 let mut present = vec![0_u64; nanos.len().div_ceil(64)];
24215 let filled: Vec<i64> = nanos
24216 .iter()
24217 .enumerate()
24218 .map(|(i, &ns)| {
24219 if ns == NAT {
24220 0
24221 } else {
24222 present[i / 64] |= 1 << (i % 64);
24223 ns
24224 }
24225 })
24226 .collect();
24227 let expected = PandasReductions::new(
24228 ReductionValues::Int(&filled),
24229 Some(&present),
24230 MissingLayout::Numpy,
24231 )
24232 .mean();
24233 assert_eq!(
24234 PandasReductions::int64_mean_skipping(&nanos, NAT).to_bits(),
24235 expected.to_bits()
24236 );
24237 assert!(PandasReductions::int64_mean_skipping(&[NAT, NAT], NAT).is_nan());
24239 assert!(PandasReductions::int64_mean_skipping(&[], NAT).is_nan());
24240 }
24241}
24242
24243#[cfg(test)]
24247mod pandas_decimal_py3c0 {
24248 use super::{PandasDecimal, pandas_decimal_to_f64, pandas_int_to_f64};
24249
24250 fn bits(token: &str) -> u64 {
24251 match pandas_decimal_to_f64(token.as_bytes()) {
24252 PandasDecimal::Value(value) => value.to_bits(),
24253 other => panic!("{token:?}: {other:?}"),
24254 }
24255 }
24256
24257 #[test]
24258 fn tokens_convert_to_pandas_bits() {
24259 let cases = [
24260 ("9.890295358649789", 0x4023_c7d4_cb12_5ce4),
24261 ("0.8690736625851781286570704999", 0x3feb_cf73_91d3_c8f1),
24262 ("0.000000068288360759838675650889", 0x3e72_54bd_8bcd_610b),
24263 ("-0.0080749473608410608782560", 0xbf80_8999_16a7_63f3),
24264 ("99999999999999999", 0x4376_3457_85d8_a001),
24265 ("1234567890123456789012345", 0x44f0_56e0_f36a_6444),
24266 ("00000000000000000.5", 0x0000_0000_0000_0000),
24268 ("-00000000000000000.5", 0x8000_0000_0000_0000),
24269 ("1.5E+10", 0x420b_f08e_b000_0000),
24270 ("-.5e-3", 0xbf40_624d_d2f1_a9fc),
24271 ("5.", 0x4014_0000_0000_0000),
24272 ("1e-320", 0x0000_0000_0000_07e8),
24273 ("2.5e-310", 0x0000_2e05_5c9a_3f6c),
24274 ("-1e-400", 0x8000_0000_0000_0000),
24275 ("-1e-700", 0x0000_0000_0000_0000),
24277 ("1e-4294967296", 0x3ff0_0000_0000_0000),
24279 ("1.7976931348623157e308", 0x7fef_ffff_ffff_ffff),
24280 ("0.001e310", 0x7fac_7b1f_3cac_7433),
24281 ];
24282 for (token, expected) in cases {
24283 assert_eq!(bits(token), expected, "{token:?}");
24284 }
24285 let correctly_rounded: f64 = "9.890295358649789".parse().unwrap();
24287 assert_ne!(correctly_rounded.to_bits(), 0x4023_c7d4_cb12_5ce4);
24288 }
24289
24290 #[test]
24291 fn what_pandas_does_not_read_as_a_float() {
24292 for token in [
24293 "1e309",
24294 "0e400",
24295 "1.8e308",
24296 "1e+0000000000000000001",
24297 "1e-2147483649",
24298 "1e",
24299 "1e+",
24300 "1.5d3",
24301 "0x10",
24302 "1_000.5",
24303 "1..5",
24304 ] {
24305 assert_eq!(
24306 pandas_decimal_to_f64(token.as_bytes()),
24307 PandasDecimal::Rejected,
24308 "{token:?}"
24309 );
24310 }
24311 for token in ["inf", "-Infinity", "nan", ".", "-", "e5", "+.e1", "--1", ""] {
24312 assert_eq!(
24313 pandas_decimal_to_f64(token.as_bytes()),
24314 PandasDecimal::NotDecimal,
24315 "{token:?}"
24316 );
24317 }
24318 }
24319
24320 #[test]
24321 fn an_integer_in_a_float_column_takes_the_same_conversion() {
24322 assert_eq!(pandas_int_to_f64(-42).to_bits(), (-42.0_f64).to_bits());
24323 assert_eq!(
24324 pandas_int_to_f64(99_999_999_999_999_999).to_bits(),
24325 0x4376_3457_85d8_a001
24326 );
24327 assert_eq!(
24328 pandas_int_to_f64(-99_999_999_999_999_999).to_bits(),
24329 0xc376_3457_85d8_a001
24330 );
24331 }
24332
24333 #[test]
24340 fn calendar_months_match_chrono_relativedelta_4g57c() {
24341 use chrono::{Datelike, NaiveDate};
24342
24343 use super::add_calendar_months_nanos;
24344 let reference = |nanos: i64, months: i64| -> Option<i64> {
24345 let at = chrono::DateTime::from_timestamp(
24346 nanos.div_euclid(1_000_000_000),
24347 u32::try_from(nanos.rem_euclid(1_000_000_000)).ok()?,
24348 )?
24349 .naive_utc();
24350 let total = i64::from(at.year())
24351 .checked_mul(12)?
24352 .checked_add(i64::from(at.month0()))?
24353 .checked_add(months)?;
24354 let year = i32::try_from(total.div_euclid(12)).ok()?;
24355 let month = u32::try_from(total.rem_euclid(12)).ok()? + 1;
24356 let last = (28..=31)
24357 .rev()
24358 .find(|day| NaiveDate::from_ymd_opt(year, month, *day).is_some())?;
24359 NaiveDate::from_ymd_opt(year, month, at.day().min(last))?
24360 .and_time(at.time())
24361 .and_utc()
24362 .timestamp_nanos_opt()
24363 };
24364 let day_nanos = 86_400_000_000_000_i64;
24365 let mut checked = 0;
24366 for year in [1678, 1699, 1900, 1969, 1970, 2000, 2023, 2024, 2100, 2261] {
24367 for month in 1..=12 {
24368 for day in [1, 15, 27, 28, 29, 30, 31] {
24369 let Some(date) = NaiveDate::from_ymd_opt(year, month, day) else {
24370 continue;
24371 };
24372 let Some(midnight) = date
24373 .and_hms_opt(0, 0, 0)
24374 .and_then(|at| at.and_utc().timestamp_nanos_opt())
24375 else {
24376 continue;
24377 };
24378 for time in [0, 1, 37_123_456_789, day_nanos - 1] {
24379 let nanos = midnight + time;
24380 for months in [-2400, -13, -12, -1, 0, 1, 2, 11, 12, 25, 1200] {
24381 assert_eq!(
24382 add_calendar_months_nanos(nanos, months),
24383 reference(nanos, months),
24384 "{nanos} + {months} months"
24385 );
24386 checked += 1;
24387 }
24388 }
24389 }
24390 }
24391 }
24392 assert!(checked > 30_000, "{checked}");
24393 let last = i64::MAX - 1;
24395 assert_eq!(add_calendar_months_nanos(last, 1), None);
24396 assert_eq!(reference(last, 1), None);
24397 assert_eq!(add_calendar_months_nanos(i64::MIN + 1, -1), None);
24398 assert_eq!(add_calendar_months_nanos(0, i64::MAX), None);
24399 assert_eq!(add_calendar_months_nanos(0, i64::MIN), None);
24400 assert_eq!(add_calendar_months_nanos(0, 12 * 400), None);
24401 assert_eq!(super::add_calendar_months_days(i64::MAX, 1), None);
24402 assert_eq!(super::add_calendar_months_days(0, i64::MAX), None);
24403 let jan31 = 19_753 * day_nanos;
24405 assert_eq!(
24406 add_calendar_months_nanos(jan31, 1),
24407 Some(19_782 * day_nanos)
24408 );
24409 }
24410
24411 #[test]
24417 fn numbered_host_values_compare_and_hash_by_number_jq8qb() {
24418 use std::hash::{Hash, Hasher};
24419
24420 use super::{HostObject, HostValue, ObjectValue};
24421
24422 struct Numbered(Option<i64>, &'static str);
24423 impl HostObject for Numbered {
24424 fn host_eq(&self, other: &dyn HostObject) -> bool {
24425 other
24426 .as_any()
24427 .downcast_ref::<Self>()
24428 .is_some_and(|other| other.1 == self.1)
24429 }
24430 fn host_repr(&self) -> String {
24431 self.1.to_owned()
24432 }
24433 fn host_str(&self) -> String {
24434 self.1.to_owned()
24435 }
24436 fn host_hash(&self) -> Option<u64> {
24437 Some(self.1.len() as u64)
24438 }
24439 fn host_cmp(&self, _other: &dyn HostObject) -> Option<std::cmp::Ordering> {
24440 None
24441 }
24442 fn as_any(&self) -> &dyn std::any::Any {
24443 self
24444 }
24445 fn host_number(&self) -> Option<i64> {
24446 self.0
24447 }
24448 }
24449 let hash = |value: &ObjectValue| {
24450 let mut hasher = std::hash::DefaultHasher::new();
24451 value.hash(&mut hasher);
24452 hasher.finish()
24453 };
24454 let cell = |number, name| ObjectValue::Host(HostValue::new(Numbered(number, name)));
24455 assert_eq!(cell(Some(7), "a"), cell(Some(7), "b"));
24456 assert_eq!(hash(&cell(Some(7), "a")), hash(&cell(Some(7), "bb")));
24457 assert_ne!(cell(Some(7), "a"), cell(Some(8), "a"));
24458 assert_eq!(cell(Some(7), "a"), cell(None, "a"));
24459 assert_ne!(cell(Some(7), "a"), cell(None, "b"));
24460 assert_eq!(cell(None, "a"), cell(None, "a"));
24461 assert_ne!(cell(None, "a"), cell(None, "b"));
24462 assert_eq!(hash(&cell(None, "ab")), hash(&cell(None, "cd")));
24463 }
24464
24465 #[test]
24466 fn interval_parse_rejects_multibyte_and_malformed_inputs_without_panic_4qg5w_13() {
24467 use super::{Interval, IntervalClosed, TypeError};
24468 for bad in [
24469 "",
24470 " ",
24471 "€€",
24472 "€€€€€",
24473 "[αβγ]",
24474 "(α, β]",
24475 "[1, 2, 3]",
24476 "[1 2]",
24477 "]1, 2[",
24478 ] {
24479 let err = Interval::parse(bad).expect_err("malformed interval must return Err");
24480 assert!(matches!(err, TypeError::ValueNotParseable { .. }));
24481 }
24482 let parsed = Interval::parse(" [1.5, 3.5) ").expect("valid interval");
24484 assert_eq!(parsed.left, 1.5);
24485 assert_eq!(parsed.right, 3.5);
24486 assert_eq!(parsed.closed, IntervalClosed::Left);
24487 }
24488
24489 #[test]
24490 fn period_scalar_calendar_asfreq_to_timestamp_and_interval_closed_open_match_pandas_uo1wg() {
24491 use super::{Interval, IntervalClosed, Period, PeriodFreq, Timestamp};
24492
24493 let right = Interval::new(0.0, 5.0, IntervalClosed::Right);
24495 assert!(!right.closed_left());
24496 assert!(right.closed_right());
24497 assert!(right.open_left());
24498 assert!(!right.open_right());
24499
24500 let left = Interval::new(0.0, 5.0, IntervalClosed::Left);
24501 assert!(left.closed_left());
24502 assert!(!left.closed_right());
24503 assert!(!left.open_left());
24504 assert!(left.open_right());
24505
24506 let both = Interval::new(0.0, 5.0, IntervalClosed::Both);
24507 assert!(both.closed_left());
24508 assert!(both.closed_right());
24509 assert!(!both.open_left());
24510 assert!(!both.open_right());
24511
24512 let neither = Interval::new(0.0, 5.0, IntervalClosed::Neither);
24513 assert!(!neither.closed_left());
24514 assert!(!neither.closed_right());
24515 assert!(neither.open_left());
24516 assert!(neither.open_right());
24517
24518 let p_m = Period::parse("2024-03").expect("2024-03");
24520 assert_eq!(p_m.year(), Some(2024));
24521 assert_eq!(p_m.month(), Some(3));
24522 assert_eq!(p_m.day(), Some(31));
24523 assert_eq!(p_m.hour(), Some(0));
24524 assert_eq!(p_m.minute(), Some(0));
24525 assert_eq!(p_m.second(), Some(0));
24526 assert_eq!(p_m.quarter(), Some(1));
24527 assert_eq!(p_m.qyear(), Some(2024));
24528 assert_eq!(p_m.weekday(), Some(6));
24529 assert_eq!(p_m.dayofweek(), Some(6));
24530 assert_eq!(p_m.day_of_week(), Some(6));
24531 assert_eq!(p_m.dayofyear(), Some(91));
24532 assert_eq!(p_m.day_of_year(), Some(91));
24533 assert_eq!(p_m.days_in_month(), Some(31));
24534 assert_eq!(p_m.daysinmonth(), Some(31));
24535 assert_eq!(p_m.week(), Some(13));
24536 assert_eq!(p_m.weekofyear(), Some(13));
24537 assert_eq!(p_m.is_leap_year(), Some(true));
24538 assert_eq!(p_m.start_time().value(), 1_709_251_200_000_000_000);
24539 assert_eq!(p_m.end_time().value(), 1_711_929_599_999_999_999);
24540 assert_eq!(p_m.to_timestamp("start").unwrap(), p_m.start_time());
24541 assert_eq!(p_m.to_timestamp("end").unwrap(), p_m.end_time());
24542 assert_eq!(
24543 p_m.asfreq("D").unwrap(),
24544 Period::parse("2024-03-31").unwrap()
24545 );
24546 assert_eq!(
24547 p_m.asfreq_with_how("D", "start").unwrap(),
24548 Period::parse("2024-03-01").unwrap()
24549 );
24550 assert_eq!(p_m.strftime("%Y-%m-%d"), "2024-03-31");
24551
24552 let ts_feb = Timestamp::parse("2024-02-15").unwrap();
24554 let p_qjan = ts_feb.to_period("Q-JAN").unwrap();
24555 assert_eq!(p_qjan.to_string(), "2025Q1");
24556 assert_eq!(p_qjan.year(), Some(2024));
24557 assert_eq!(p_qjan.qyear(), Some(2025));
24558 assert_eq!(p_qjan.quarter(), Some(1));
24559 assert_eq!(p_qjan.month(), Some(4));
24560 assert_eq!(p_qjan.day(), Some(30));
24561 assert_eq!(p_qjan.days_in_month(), Some(30));
24562 assert_eq!(p_qjan.start_time().value(), 1_706_745_600_000_000_000);
24563 assert_eq!(p_qjan.end_time().value(), 1_714_521_599_999_999_999);
24564 assert_eq!(p_qjan.strftime("%Y-%m-%d"), "2024-04-30");
24565
24566 let p_fri = Timestamp::parse("2024-03-15")
24568 .unwrap()
24569 .to_period("B")
24570 .unwrap();
24571 assert_eq!(p_fri.day(), Some(15));
24572 assert_eq!(p_fri.weekday(), Some(4));
24573 assert_eq!(
24574 p_fri.end_time().value(),
24575 p_fri.start_time().value() + 86_400_000_000_000 - 1
24576 );
24577 assert_eq!(
24578 p_fri.asfreq_with_how("D", "E").unwrap(),
24579 Period::parse("2024-03-15").unwrap()
24580 );
24581
24582 let p_now = Period::now("D").expect("Period::now(D)");
24584 assert_eq!(p_now.freq(), PeriodFreq::Daily);
24585 assert!(!p_now.is_nat());
24586
24587 let p_nat = Period::new(i64::MIN, PeriodFreq::Monthly);
24589 assert!(p_nat.is_nat());
24590 assert_eq!(p_nat.year(), None);
24591 assert_eq!(p_nat.qyear(), None);
24592 assert_eq!(p_nat.quarter(), None);
24593 assert_eq!(p_nat.is_leap_year(), None);
24594 assert!(p_nat.start_time().is_nat());
24595 assert!(p_nat.end_time().is_nat());
24596 assert_eq!(p_nat.strftime("%Y-%m-%d"), "NaT");
24597 assert!(p_nat.asfreq("D").unwrap().is_nat());
24598 assert_eq!(p_nat.asfreq("D").unwrap().freq(), PeriodFreq::Daily);
24599 assert!(p_m.asfreq("NOT_A_FREQ").is_err());
24600 assert!(p_m.asfreq_with_how("D", "middle").is_err());
24601 assert!(p_m.to_timestamp("middle").is_err());
24602 assert!(Timestamp::nat().to_period("D").is_err());
24603 }
24604
24605 #[test]
24606 fn timestamp_tz_localize_convert_isoformat_tzname_and_getters_match_pandas_sddfo() {
24607 use crate::{TimeZoneError, Timestamp, TypeError};
24608
24609 let ts_naive = Timestamp::parse("2024-01-01T03:30:00").unwrap();
24611 assert_eq!(ts_naive.value(), 1_704_079_800_000_000_000);
24612 assert_eq!(ts_naive.tzname(), None);
24613
24614 let ts_ny = ts_naive.tz_localize(Some("America/New_York"));
24615 assert_eq!(ts_ny.value(), 1_704_097_800_000_000_000);
24616 assert_eq!(ts_ny.isoformat(), "2024-01-01T03:30:00-05:00");
24617 assert_eq!(ts_ny.tzname().as_deref(), Some("EST"));
24618 assert_eq!(ts_ny.year(), Some(2024));
24619 assert_eq!(ts_ny.month(), Some(1));
24620 assert_eq!(ts_ny.day(), Some(1));
24621 assert_eq!(ts_ny.hour(), Some(3));
24622 assert_eq!(ts_ny.minute(), Some(30));
24623
24624 let ts_utc = Timestamp::parse("2024-01-01T03:30:00Z").unwrap();
24626 let ts_from_utc = ts_utc.tz_convert("America/New_York");
24627 assert_eq!(ts_from_utc.value(), 1_704_079_800_000_000_000);
24628 assert_eq!(ts_from_utc.isoformat(), "2023-12-31T22:30:00-05:00");
24629 assert_eq!(ts_from_utc.tzname().as_deref(), Some("EST"));
24630 assert_eq!(ts_from_utc.year(), Some(2023));
24631 assert_eq!(ts_from_utc.month(), Some(12));
24632 assert_eq!(ts_from_utc.day(), Some(31));
24633 assert_eq!(ts_from_utc.hour(), Some(22));
24634 assert_eq!(ts_from_utc.minute(), Some(30));
24635 assert_eq!(ts_from_utc.dayofweek(), Some(6));
24636 assert_eq!(ts_from_utc.day_name(), "Sunday");
24637 assert_eq!(ts_from_utc.month_name(), "December");
24638 assert_eq!(ts_from_utc.toordinal(), Some(738_885));
24639 assert_eq!(ts_from_utc.is_year_end(), Some(true));
24640 assert_eq!(ts_from_utc.is_year_start(), Some(false));
24641
24642 let stripped = ts_from_utc.tz_localize(None);
24644 assert_eq!(stripped.tzinfo(), None);
24645 assert_eq!(stripped.value(), 1_704_061_800_000_000_000);
24646 assert_eq!(stripped.isoformat(), "2023-12-31T22:30:00");
24647
24648 let ts_summer = Timestamp::parse("2024-07-01T12:00:00")
24650 .unwrap()
24651 .tz_localize(Some("America/New_York"));
24652 assert_eq!(ts_summer.isoformat(), "2024-07-01T12:00:00-04:00");
24653 assert_eq!(ts_summer.tzname().as_deref(), Some("EDT"));
24654
24655 let replaced = ts_from_utc.replace(Some(2025), None, None, None, None, None, None, None);
24657 assert_eq!(replaced.value(), 1_767_238_200_000_000_000);
24658 assert_eq!(replaced.isoformat(), "2025-12-31T22:30:00-05:00");
24659
24660 assert_eq!(
24662 ts_ny.try_tz_localize(Some("UTC")),
24663 Err(TypeError::AlreadyTzAware)
24664 );
24665 assert!(ts_ny.tz_localize(Some("UTC")).is_nat());
24666 assert_eq!(
24667 ts_naive.try_tz_convert(Some("UTC")),
24668 Err(TypeError::TzNaiveCannotConvert)
24669 );
24670 assert!(ts_naive.tz_convert("UTC").is_nat());
24671 assert!(matches!(
24672 ts_naive.try_tz_localize(Some("Mars/Olympus")),
24673 Err(TypeError::TimeZone(TimeZoneError::Unknown(_)))
24674 ));
24675 assert!(matches!(
24676 ts_ny.try_tz_convert(Some("Mars/Olympus")),
24677 Err(TypeError::TimeZone(TimeZoneError::Unknown(_)))
24678 ));
24679 }
24680}