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}
2059
2060impl SparseDType {
2061 pub fn new(value_dtype: DType, fill_value: Scalar) -> Result<Self, TypeError> {
2067 if matches!(value_dtype, DType::Null | DType::Sparse) {
2068 return Err(TypeError::InvalidSparseValueDType { dtype: value_dtype });
2069 }
2070
2071 let fill_value = if fill_value.is_missing() {
2072 Scalar::missing_for_dtype(value_dtype.clone())
2073 } else {
2074 cast_scalar_owned(fill_value, value_dtype.clone())?
2075 };
2076
2077 Ok(Self {
2078 value_dtype,
2079 fill_value,
2080 })
2081 }
2082
2083 #[must_use]
2110 pub fn pandas_name(&self) -> String {
2111 format!(
2112 "Sparse[{}, {}]",
2113 self.value_dtype.name(),
2114 scalar_to_string_for_astype(self.fill_value.clone())
2115 )
2116 }
2117}
2118
2119impl AsDType for SparseDType {
2120 fn as_dtype(&self) -> DType {
2121 DType::Sparse
2122 }
2123}
2124
2125#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
2129pub struct CategoricalDtype {
2130 pub categories: Option<Vec<String>>,
2131 pub ordered: bool,
2132}
2133
2134pub type CategoricalDType = CategoricalDtype;
2135
2136impl CategoricalDtype {
2137 #[must_use]
2139 pub const fn new(categories: Option<Vec<String>>, ordered: bool) -> Self {
2140 Self {
2141 categories,
2142 ordered,
2143 }
2144 }
2145
2146 #[must_use]
2148 pub fn categories(&self) -> Option<&[String]> {
2149 self.categories.as_deref()
2150 }
2151
2152 #[must_use]
2154 pub const fn ordered(&self) -> bool {
2155 self.ordered
2156 }
2157
2158 #[must_use]
2160 pub const fn name(&self) -> &'static str {
2161 "category"
2162 }
2163
2164 #[must_use]
2166 pub const fn kind(&self) -> &'static str {
2167 "O"
2168 }
2169}
2170
2171impl AsDType for CategoricalDtype {
2172 fn as_dtype(&self) -> DType {
2173 DType::Categorical
2174 }
2175}
2176
2177impl std::fmt::Display for CategoricalDtype {
2178 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2179 let ord_str = if self.ordered { "True" } else { "False" };
2180 match &self.categories {
2181 Some(cats) => write!(
2182 f,
2183 "CategoricalDtype(categories={cats:?}, ordered={ord_str})"
2184 ),
2185 None => write!(f, "CategoricalDtype(categories=None, ordered={ord_str})"),
2186 }
2187 }
2188}
2189
2190#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
2194pub struct PeriodDtype {
2195 pub freq: String,
2196}
2197
2198pub type PeriodDType = PeriodDtype;
2199
2200impl PeriodDtype {
2201 #[must_use]
2203 pub fn new(freq: impl Into<String>) -> Self {
2204 Self { freq: freq.into() }
2205 }
2206
2207 #[must_use]
2209 pub fn freq(&self) -> &str {
2210 &self.freq
2211 }
2212
2213 #[must_use]
2215 pub fn name(&self) -> String {
2216 format!("period[{}]", self.freq)
2217 }
2218
2219 #[must_use]
2221 pub const fn kind(&self) -> &'static str {
2222 "O"
2223 }
2224}
2225
2226impl Default for PeriodDtype {
2227 fn default() -> Self {
2228 Self {
2229 freq: "D".to_string(),
2230 }
2231 }
2232}
2233
2234impl AsDType for PeriodDtype {
2235 fn as_dtype(&self) -> DType {
2236 DType::Period
2237 }
2238}
2239
2240impl std::fmt::Display for PeriodDtype {
2241 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2242 write!(f, "period[{}]", self.freq)
2243 }
2244}
2245
2246#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2250pub struct IntervalDtype {
2251 pub subtype: DType,
2252 pub closed: Option<IntervalClosed>,
2253}
2254
2255pub type IntervalDType = IntervalDtype;
2256
2257impl IntervalDtype {
2258 #[must_use]
2260 pub const fn new(subtype: DType, closed: Option<IntervalClosed>) -> Self {
2261 Self { subtype, closed }
2262 }
2263
2264 #[must_use]
2266 pub const fn subtype(&self) -> &DType {
2267 &self.subtype
2268 }
2269
2270 #[must_use]
2272 pub const fn closed(&self) -> Option<IntervalClosed> {
2273 self.closed
2274 }
2275
2276 #[must_use]
2278 pub const fn name(&self) -> &'static str {
2279 "interval"
2280 }
2281
2282 #[must_use]
2284 pub const fn kind(&self) -> &'static str {
2285 "O"
2286 }
2287}
2288
2289impl Default for IntervalDtype {
2290 fn default() -> Self {
2291 Self {
2292 subtype: DType::Float64,
2293 closed: Some(IntervalClosed::Right),
2294 }
2295 }
2296}
2297
2298impl AsDType for IntervalDtype {
2299 fn as_dtype(&self) -> DType {
2300 DType::Interval
2301 }
2302}
2303
2304impl std::fmt::Display for IntervalDtype {
2305 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2306 match self.closed {
2307 Some(c) => write!(f, "interval[{}, {c}]", self.subtype.name()),
2308 None => write!(f, "interval[{}]", self.subtype.name()),
2309 }
2310 }
2311}
2312
2313#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
2314#[serde(rename_all = "snake_case")]
2315pub enum NullKind {
2316 Null,
2317 NaN,
2318 NaT,
2319}
2320
2321mod float64_json {
2329 use serde::{Deserialize, Deserializer, Serializer, de::Error as _};
2330
2331 pub fn serialize<S: Serializer>(value: &f64, serializer: S) -> Result<S::Ok, S::Error> {
2332 if value.is_infinite() {
2333 serializer.serialize_str(if value.is_sign_positive() {
2334 "inf"
2335 } else {
2336 "-inf"
2337 })
2338 } else {
2339 serializer.serialize_f64(*value)
2340 }
2341 }
2342
2343 #[derive(Deserialize)]
2344 #[serde(untagged)]
2345 enum Repr {
2346 Number(f64),
2347 Text(String),
2348 Null(()),
2349 }
2350
2351 pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<f64, D::Error> {
2352 match Repr::deserialize(deserializer)? {
2353 Repr::Number(value) => Ok(value),
2354 Repr::Text(text) => match text.as_str() {
2355 "inf" => Ok(f64::INFINITY),
2356 "-inf" => Ok(f64::NEG_INFINITY),
2357 other => Err(D::Error::custom(format!(
2358 "float64 value must be a number, \"inf\" or \"-inf\", got {other:?}"
2359 ))),
2360 },
2361 Repr::Null(()) => Ok(f64::NAN),
2362 }
2363 }
2364}
2365
2366#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2367#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
2368pub enum Scalar {
2369 Null(NullKind),
2370 Bool(bool),
2371 Int64(i64),
2372 Float64(#[serde(with = "float64_json")] f64),
2373 #[serde(alias = "string", alias = "str")]
2374 Utf8(String),
2375 Timedelta64(i64),
2376 Datetime64(i64),
2379 Period(Period),
2385 Interval(Interval),
2387 Object(ObjectValue),
2391}
2392
2393#[derive(Clone)]
2397pub enum ObjectValue {
2398 List(std::sync::Arc<[Scalar]>),
2400 Bytes(std::sync::Arc<[u8]>),
2404 Host(HostValue),
2406}
2407
2408pub trait HostObject: Send + Sync {
2411 fn host_eq(&self, other: &dyn HostObject) -> bool;
2413 fn host_repr(&self) -> String;
2415 fn host_str(&self) -> String;
2417 fn host_pprint(&self) -> String {
2421 self.host_str()
2422 }
2423 fn host_hash(&self) -> Option<u64>;
2425 fn host_cmp(&self, other: &dyn HostObject) -> Option<std::cmp::Ordering>;
2429 fn host_eq_scalar(&self, _other: &Scalar) -> bool {
2432 false
2433 }
2434 fn host_type_name(&self) -> String {
2437 "object".to_owned()
2438 }
2439 fn as_any(&self) -> &dyn std::any::Any;
2441 fn host_number(&self) -> Option<i64> {
2447 None
2448 }
2449}
2450
2451static LIVE_HOST_VALUES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
2453
2454static HOST_LOCK_DECLARED: std::sync::atomic::AtomicBool =
2457 std::sync::atomic::AtomicBool::new(false);
2458
2459pub fn declare_host_lock() {
2463 HOST_LOCK_DECLARED.store(true, std::sync::atomic::Ordering::Relaxed);
2464}
2465
2466#[must_use]
2474pub fn host_values_block_workers() -> bool {
2475 workers_blocked(
2476 HOST_LOCK_DECLARED.load(std::sync::atomic::Ordering::Relaxed),
2477 LIVE_HOST_VALUES.load(std::sync::atomic::Ordering::Relaxed),
2478 )
2479}
2480
2481const fn workers_blocked(host_lock_declared: bool, live_host_values: usize) -> bool {
2483 host_lock_declared && live_host_values > 0
2484}
2485
2486struct HostSlot<T: ?Sized> {
2490 number: Option<i64>,
2492 object: T,
2493}
2494
2495impl<T: ?Sized> Drop for HostSlot<T> {
2496 fn drop(&mut self) {
2497 LIVE_HOST_VALUES.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
2498 }
2499}
2500
2501#[derive(Clone)]
2503pub struct HostValue(std::sync::Arc<HostSlot<dyn HostObject>>);
2504
2505impl HostValue {
2506 #[must_use]
2507 pub fn new(object: impl HostObject + 'static) -> Self {
2508 LIVE_HOST_VALUES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2509 Self(std::sync::Arc::new(HostSlot {
2510 number: object.host_number(),
2511 object,
2512 }))
2513 }
2514
2515 #[must_use]
2516 pub fn object(&self) -> &dyn HostObject {
2517 &self.0.object
2518 }
2519
2520 #[must_use]
2522 pub fn number(&self) -> Option<i64> {
2523 self.0.number
2524 }
2525}
2526
2527impl PartialEq for HostValue {
2528 fn eq(&self, other: &Self) -> bool {
2529 std::sync::Arc::ptr_eq(&self.0, &other.0)
2530 || match (self.number(), other.number()) {
2531 (Some(left), Some(right)) => left == right,
2534 _ => self.object().host_eq(other.object()),
2535 }
2536 }
2537}
2538
2539impl std::fmt::Debug for HostValue {
2540 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2541 formatter.write_str(&self.object().host_repr())
2542 }
2543}
2544
2545impl ObjectValue {
2546 #[must_use]
2548 pub fn list(items: Vec<Scalar>) -> Self {
2549 Self::List(items.into())
2550 }
2551
2552 #[must_use]
2554 pub fn as_list(&self) -> Option<&[Scalar]> {
2555 match self {
2556 Self::List(items) => Some(items),
2557 Self::Bytes(_) | Self::Host(_) => None,
2558 }
2559 }
2560
2561 #[must_use]
2563 pub fn bytes(data: Vec<u8>) -> Self {
2564 Self::Bytes(data.into())
2565 }
2566
2567 #[must_use]
2569 pub fn as_bytes(&self) -> Option<&[u8]> {
2570 match self {
2571 Self::Bytes(data) => Some(data),
2572 Self::List(_) | Self::Host(_) => None,
2573 }
2574 }
2575
2576 #[must_use]
2578 pub fn repr(&self) -> String {
2579 match self {
2580 Self::List(items) => {
2581 let parts: Vec<String> = items.iter().map(Scalar::python_repr).collect();
2582 format!("[{}]", parts.join(", "))
2583 }
2584 Self::Bytes(data) => python_bytes_repr(data),
2585 Self::Host(value) => value.object().host_repr(),
2586 }
2587 }
2588
2589 #[must_use]
2592 pub fn pprint(&self) -> String {
2593 match self {
2594 Self::List(items) => {
2595 let parts: Vec<String> = items
2596 .iter()
2597 .map(|item| match item {
2598 Scalar::Utf8(text) => text.clone(),
2599 Scalar::Object(object) => object.pprint(),
2600 other => other.python_repr(),
2601 })
2602 .collect();
2603 format!("[{}]", parts.join(", "))
2604 }
2605 Self::Bytes(data) => python_bytes_repr(data),
2606 Self::Host(value) => value.object().host_pprint(),
2607 }
2608 }
2609
2610 #[must_use]
2613 pub fn type_name(&self) -> String {
2614 match self {
2615 Self::List(_) => "list".to_owned(),
2616 Self::Bytes(_) => "bytes".to_owned(),
2617 Self::Host(value) => value.object().host_type_name(),
2618 }
2619 }
2620
2621 #[must_use]
2625 pub fn python_eq_scalar(&self, other: &Scalar) -> bool {
2626 match self {
2627 Self::Host(value) => value.object().host_eq_scalar(other),
2628 Self::List(_) | Self::Bytes(_) => false,
2629 }
2630 }
2631
2632 #[must_use]
2636 pub fn python_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
2637 match (self, other) {
2638 (Self::Bytes(left), Self::Bytes(right)) => Some(left.cmp(right)),
2639 (Self::Host(left), Self::Host(right)) => {
2640 if left == right {
2641 Some(std::cmp::Ordering::Equal)
2642 } else {
2643 left.object().host_cmp(right.object())
2644 }
2645 }
2646 (Self::List(left), Self::List(right)) => {
2647 for (a, b) in left.iter().zip(right.iter()) {
2648 if a != b {
2649 let ordering = a.python_cmp(b)?;
2650 if ordering.is_ne() {
2651 return Some(ordering);
2652 }
2653 }
2654 }
2655 Some(left.len().cmp(&right.len()))
2656 }
2657 _ => None,
2658 }
2659 }
2660
2661 #[must_use]
2666 pub fn total_cmp(&self, other: &Self) -> std::cmp::Ordering {
2667 use std::cmp::Ordering;
2668 if self == other {
2669 return Ordering::Equal;
2670 }
2671 if let Some(ordering) = self.python_cmp(other).filter(|ordering| ordering.is_ne()) {
2672 return ordering;
2673 }
2674 let rank = |cell: &Self| match cell {
2675 Self::List(_) => 0_u8,
2676 Self::Bytes(_) => 1,
2677 Self::Host(_) => 2,
2678 };
2679 rank(self)
2680 .cmp(&rank(other))
2681 .then_with(|| self.repr().cmp(&other.repr()))
2682 .then_with(|| self.address().cmp(&other.address()))
2683 }
2684
2685 fn address(&self) -> usize {
2688 match self {
2689 Self::List(items) => items.as_ptr().addr(),
2690 Self::Bytes(data) => data.as_ptr().addr(),
2691 Self::Host(value) => std::sync::Arc::as_ptr(&value.0).cast::<()>().addr(),
2692 }
2693 }
2694}
2695
2696#[must_use]
2700pub fn python_bytes_repr(data: &[u8]) -> String {
2701 let quote = if data.contains(&b'\'') && !data.contains(&b'"') {
2702 b'"'
2703 } else {
2704 b'\''
2705 };
2706 let mut out = String::with_capacity(data.len() + 3);
2707 out.push('b');
2708 out.push(char::from(quote));
2709 for &byte in data {
2710 match byte {
2711 b'\\' => out.push_str("\\\\"),
2712 b'\t' => out.push_str("\\t"),
2713 b'\n' => out.push_str("\\n"),
2714 b'\r' => out.push_str("\\r"),
2715 _ if byte == quote => {
2716 out.push('\\');
2717 out.push(char::from(byte));
2718 }
2719 0x20..=0x7e => out.push(char::from(byte)),
2720 _ => out.push_str(&format!("\\x{byte:02x}")),
2721 }
2722 }
2723 out.push(char::from(quote));
2724 out
2725}
2726
2727impl PartialOrd for ObjectValue {
2728 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
2729 Some(self.cmp(other))
2730 }
2731}
2732
2733impl Ord for ObjectValue {
2735 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
2736 self.total_cmp(other)
2737 }
2738}
2739
2740impl PartialEq for ObjectValue {
2741 fn eq(&self, other: &Self) -> bool {
2742 match (self, other) {
2743 (Self::List(left), Self::List(right)) => left == right,
2744 (Self::Bytes(left), Self::Bytes(right)) => left == right,
2745 (Self::Host(left), Self::Host(right)) => left == right,
2746 _ => false,
2747 }
2748 }
2749}
2750
2751impl Eq for ObjectValue {}
2755
2756impl std::hash::Hash for ObjectValue {
2757 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
2758 match self {
2759 Self::List(items) => {
2760 0_u8.hash(state);
2761 for item in items.iter() {
2762 item.python_repr().hash(state);
2763 }
2764 }
2765 Self::Bytes(data) => {
2766 2_u8.hash(state);
2767 data.hash(state);
2768 }
2769 Self::Host(value) => {
2770 1_u8.hash(state);
2771 if let Some(number) = value.number() {
2774 number.hash(state);
2775 return;
2776 }
2777 match value.object().host_hash() {
2778 Some(hash) => hash.hash(state),
2779 None => value.object().host_repr().hash(state),
2780 }
2781 }
2782 }
2783 }
2784}
2785
2786impl std::fmt::Debug for ObjectValue {
2787 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2788 formatter.write_str(&self.repr())
2789 }
2790}
2791
2792impl std::fmt::Display for ObjectValue {
2796 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2797 match self {
2798 Self::List(_) | Self::Bytes(_) => formatter.write_str(&self.repr()),
2799 Self::Host(value) => formatter.write_str(&value.object().host_str()),
2800 }
2801 }
2802}
2803
2804impl Serialize for ObjectValue {
2807 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2808 match self {
2809 Self::List(items) => items.as_ref().serialize(serializer),
2810 Self::Bytes(data) => SerializedObject::Bytes {
2811 bytes: data.to_vec(),
2812 }
2813 .serialize(serializer),
2814 Self::Host(_) => Err(serde::ser::Error::custom(
2815 "a host-language object cell cannot be serialized",
2816 )),
2817 }
2818 }
2819}
2820
2821#[derive(Serialize, Deserialize)]
2824#[serde(untagged)]
2825enum SerializedObject {
2826 List(Vec<Scalar>),
2827 Bytes { bytes: Vec<u8> },
2828}
2829
2830impl<'de> Deserialize<'de> for ObjectValue {
2831 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
2832 Ok(match SerializedObject::deserialize(deserializer)? {
2833 SerializedObject::List(items) => Self::list(items),
2834 SerializedObject::Bytes { bytes } => Self::bytes(bytes),
2835 })
2836 }
2837}
2838
2839impl std::fmt::Display for Scalar {
2840 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2841 match self {
2842 Self::Null(NullKind::NaN) => write!(f, "NaN"),
2843 Self::Null(NullKind::NaT) => write!(f, "NaT"),
2844 Self::Null(NullKind::Null) => write!(f, "None"),
2845 Self::Bool(b) => write!(f, "{}", if *b { "True" } else { "False" }),
2846 Self::Int64(v) => write!(f, "{v}"),
2847 Self::Float64(v) => write!(f, "{v}"),
2848 Self::Utf8(s) => write!(f, "{s}"),
2849 Self::Timedelta64(nanos) => write!(f, "{}", Timedelta::format(*nanos)),
2850 Self::Datetime64(nanos) => {
2851 if *nanos == Timestamp::NAT {
2852 write!(f, "NaT")
2853 } else {
2854 write!(f, "Timestamp[{nanos}]")
2855 }
2856 }
2857 Self::Period(p) => {
2858 if p.ordinal == i64::MIN {
2859 write!(f, "NaT")
2860 } else {
2861 write!(f, "{}", p.calendar_string())
2862 }
2863 }
2864 Self::Interval(interval) => write!(f, "{interval}"),
2865 Self::Object(object) => write!(f, "{object}"),
2866 }
2867 }
2868}
2869
2870impl Scalar {
2871 #[must_use]
2878 pub fn python_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
2879 let numeric =
2880 |value: &Self| matches!(value, Self::Bool(_) | Self::Int64(_) | Self::Float64(_));
2881 match (self, other) {
2882 (Self::Utf8(a), Self::Utf8(b)) => Some(a.cmp(b)),
2883 (Self::Datetime64(a), Self::Datetime64(b))
2884 | (Self::Timedelta64(a), Self::Timedelta64(b)) => Some(a.cmp(b)),
2885 (Self::Period(a), Self::Period(b)) if a.freq == b.freq => {
2886 Some(a.ordinal.cmp(&b.ordinal))
2887 }
2888 (Self::Interval(a), Self::Interval(b)) => Some(
2889 a.left
2890 .partial_cmp(&b.left)?
2891 .then(a.right.partial_cmp(&b.right)?),
2892 ),
2893 (Self::Object(a), Self::Object(b)) => a.python_cmp(b),
2894 _ if numeric(self) && numeric(other) => {
2895 self.to_f64().ok()?.partial_cmp(&other.to_f64().ok()?)
2896 }
2897 _ => None,
2898 }
2899 }
2900
2901 #[must_use]
2906 pub fn python_cmp_type_names(&self, other: &Self) -> (String, String) {
2907 if let (Self::Object(ObjectValue::List(left)), Self::Object(ObjectValue::List(right))) =
2908 (self, other)
2909 && let Some((a, b)) = left.iter().zip(right.iter()).find(|(a, b)| a != b)
2910 {
2911 return a.python_cmp_type_names(b);
2912 }
2913 (self.python_type_name(), other.python_type_name())
2914 }
2915
2916 #[must_use]
2919 pub fn python_type_name(&self) -> String {
2920 match self {
2921 Self::Null(NullKind::NaN) | Self::Float64(_) => "float",
2922 Self::Null(NullKind::NaT) => "NaTType",
2923 Self::Null(NullKind::Null) => "NoneType",
2924 Self::Bool(_) => "bool",
2925 Self::Int64(_) => "int",
2926 Self::Utf8(_) => "str",
2927 Self::Timedelta64(_) => "Timedelta",
2928 Self::Datetime64(_) => "Timestamp",
2929 Self::Period(_) => "Period",
2930 Self::Interval(_) => "Interval",
2931 Self::Object(object) => return object.type_name(),
2932 }
2933 .to_owned()
2934 }
2935
2936 #[must_use]
2940 pub fn python_repr(&self) -> String {
2941 match self {
2942 Self::Null(NullKind::NaN) => "nan".to_owned(),
2943 Self::Null(NullKind::NaT) => "NaT".to_owned(),
2944 Self::Null(NullKind::Null) => "None".to_owned(),
2945 Self::Utf8(text) => {
2946 let quote = if text.contains('\'') && !text.contains('"') {
2947 '"'
2948 } else {
2949 '\''
2950 };
2951 let mut out = String::with_capacity(text.len() + 2);
2952 out.push(quote);
2953 for ch in text.chars() {
2954 match ch {
2955 '\\' => out.push_str("\\\\"),
2956 '\n' => out.push_str("\\n"),
2957 '\r' => out.push_str("\\r"),
2958 '\t' => out.push_str("\\t"),
2959 c if c == quote => {
2960 out.push('\\');
2961 out.push(c);
2962 }
2963 c => out.push(c),
2964 }
2965 }
2966 out.push(quote);
2967 out
2968 }
2969 Self::Float64(value) => {
2970 if value.is_nan() {
2971 "nan".to_owned()
2972 } else if value.is_infinite() {
2973 if *value > 0.0 { "inf" } else { "-inf" }.to_owned()
2974 } else if value.fract() == 0.0 && value.abs() < 1e16 {
2975 format!("{value:.1}")
2976 } else {
2977 format!("{value}")
2978 }
2979 }
2980 Self::Object(object) => object.repr(),
2981 other => other.to_string(),
2982 }
2983 }
2984}
2985
2986pub const NA: Scalar = Scalar::Null(NullKind::Null);
2988
2989pub const NAT: Scalar = Scalar::Null(NullKind::NaT);
2991
2992#[allow(non_upper_case_globals)]
2994pub const NaT: Scalar = NAT;
2995
2996impl From<bool> for Scalar {
3006 fn from(value: bool) -> Self {
3007 Self::Bool(value)
3008 }
3009}
3010
3011impl From<i64> for Scalar {
3012 fn from(value: i64) -> Self {
3013 Self::Int64(value)
3014 }
3015}
3016
3017impl From<f64> for Scalar {
3018 fn from(value: f64) -> Self {
3019 Self::Float64(value)
3020 }
3021}
3022
3023impl From<&str> for Scalar {
3024 fn from(value: &str) -> Self {
3025 Self::Utf8(value.to_owned())
3026 }
3027}
3028
3029impl From<String> for Scalar {
3030 fn from(value: String) -> Self {
3031 Self::Utf8(value)
3032 }
3033}
3034
3035impl Scalar {
3036 #[inline]
3037 const fn debug_variant_name(&self) -> &'static str {
3038 match self {
3039 Self::Null(_) => "Null",
3040 Self::Bool(_) => "Bool",
3041 Self::Int64(_) => "Int64",
3042 Self::Float64(_) => "Float64",
3043 Self::Utf8(_) => "Utf8",
3044 Self::Timedelta64(_) => "Timedelta64",
3045 Self::Datetime64(_) => "Datetime64",
3046 Self::Period(_) => "Period",
3047 Self::Interval(_) => "Interval",
3048 Self::Object(_) => "Object",
3049 }
3050 }
3051
3052 #[must_use]
3053 pub fn dtype(&self) -> DType {
3054 match self {
3055 Self::Null(_) => DType::Null,
3056 Self::Bool(_) => DType::Bool,
3057 Self::Int64(_) => DType::Int64,
3058 Self::Float64(_) => DType::Float64,
3059 Self::Utf8(_) => DType::Utf8,
3060 Self::Timedelta64(_) => DType::Timedelta64,
3061 Self::Datetime64(_) => DType::datetime64_naive(),
3062 Self::Period(_) => DType::Period,
3063 Self::Interval(_) => DType::Interval,
3064 Self::Object(_) => DType::Utf8,
3066 }
3067 }
3068
3069 #[must_use]
3070 pub fn is_missing(&self) -> bool {
3071 match self {
3072 Self::Null(_) => true,
3073 Self::Float64(v) => v.is_nan(),
3074 Self::Timedelta64(v) => *v == Timedelta::NAT,
3075 Self::Datetime64(v) => *v == Timestamp::NAT,
3076 Self::Period(p) => p.ordinal == i64::MIN,
3077 _ => false,
3078 }
3079 }
3080
3081 #[must_use]
3082 pub fn is_nan(&self) -> bool {
3083 matches!(self, Self::Null(NullKind::NaN)) || matches!(self, Self::Float64(v) if v.is_nan())
3084 }
3085
3086 #[must_use]
3088 pub const fn is_bool(&self) -> bool {
3089 matches!(self, Self::Bool(_))
3090 }
3091
3092 #[must_use]
3094 pub const fn is_integer(&self) -> bool {
3095 matches!(self, Self::Int64(_))
3096 }
3097
3098 #[must_use]
3100 pub const fn is_float(&self) -> bool {
3101 matches!(self, Self::Float64(_))
3102 }
3103
3104 #[must_use]
3106 pub const fn is_numeric(&self) -> bool {
3107 matches!(self, Self::Int64(_) | Self::Float64(_))
3108 }
3109
3110 #[must_use]
3112 pub const fn is_string(&self) -> bool {
3113 matches!(self, Self::Utf8(_))
3114 }
3115
3116 #[must_use]
3118 pub const fn is_datetime(&self) -> bool {
3119 matches!(self, Self::Datetime64(_))
3120 }
3121
3122 #[must_use]
3124 pub const fn is_timedelta(&self) -> bool {
3125 matches!(self, Self::Timedelta64(_))
3126 }
3127
3128 #[must_use]
3130 pub const fn is_period(&self) -> bool {
3131 matches!(self, Self::Period(_))
3132 }
3133
3134 #[must_use]
3136 pub const fn is_interval(&self) -> bool {
3137 matches!(self, Self::Interval(_))
3138 }
3139
3140 #[must_use]
3142 pub const fn as_i64(&self) -> Option<i64> {
3143 match self {
3144 Self::Int64(v) => Some(*v),
3145 _ => None,
3146 }
3147 }
3148
3149 #[must_use]
3151 pub const fn as_int(&self) -> Option<i64> {
3152 self.as_i64()
3153 }
3154
3155 #[must_use]
3157 pub const fn as_f64(&self) -> Option<f64> {
3158 match self {
3159 Self::Float64(v) => Some(*v),
3160 _ => None,
3161 }
3162 }
3163
3164 #[must_use]
3166 pub const fn as_float(&self) -> Option<f64> {
3167 self.as_f64()
3168 }
3169
3170 #[must_use]
3172 pub const fn as_bool(&self) -> Option<bool> {
3173 match self {
3174 Self::Bool(v) => Some(*v),
3175 _ => None,
3176 }
3177 }
3178
3179 #[must_use]
3181 pub fn as_str(&self) -> Option<&str> {
3182 match self {
3183 Self::Utf8(s) => Some(s.as_str()),
3184 _ => None,
3185 }
3186 }
3187
3188 #[must_use]
3190 pub const fn as_datetime_nanos(&self) -> Option<i64> {
3191 match self {
3192 Self::Datetime64(v) => Some(*v),
3193 _ => None,
3194 }
3195 }
3196
3197 #[must_use]
3199 pub const fn as_timedelta_nanos(&self) -> Option<i64> {
3200 match self {
3201 Self::Timedelta64(v) => Some(*v),
3202 _ => None,
3203 }
3204 }
3205
3206 #[must_use]
3208 pub const fn as_period_ordinal(&self) -> Option<i64> {
3209 match self {
3210 Self::Period(p) => Some(p.ordinal),
3211 _ => None,
3212 }
3213 }
3214
3215 #[must_use]
3217 pub const fn as_interval(&self) -> Option<Interval> {
3218 match self {
3219 Self::Interval(i) => Some(*i),
3220 _ => None,
3221 }
3222 }
3223
3224 #[must_use]
3225 pub fn missing_for_dtype(dtype: DType) -> Self {
3226 match dtype {
3227 DType::Float64 => Self::Null(NullKind::NaN),
3228 DType::Float64Nullable => Self::Null(NullKind::Null),
3236 DType::Timedelta64 => Self::Timedelta64(Timedelta::NAT),
3237 DType::Datetime64 { .. } => Self::Datetime64(Timestamp::NAT),
3238 DType::Period => Self::Period(Period::new(i64::MIN, PeriodFreq::Daily)),
3239 DType::Null => Self::Null(NullKind::Null),
3240 DType::Bool
3241 | DType::BoolNullable
3242 | DType::Int64
3243 | DType::Int64Nullable
3244 | DType::Utf8
3245 | DType::Categorical
3246 | DType::Interval
3247 | DType::Sparse => Self::Null(NullKind::Null),
3248 }
3249 }
3250
3251 #[must_use]
3252 pub fn semantic_eq(&self, other: &Self) -> bool {
3253 match (self, other) {
3254 (Self::Float64(a), Self::Float64(b)) => {
3255 if a.is_nan() && b.is_nan() {
3256 return true;
3257 }
3258 if *a == *b {
3259 return true;
3260 }
3261 let diff = (*a - *b).abs();
3262 let max_abs = a.abs().max(b.abs());
3263 if max_abs == 0.0 {
3264 diff < f64::EPSILON
3265 } else {
3266 diff / max_abs < 1e-14
3267 }
3268 }
3269 (Self::Null(_), Self::Float64(v)) | (Self::Float64(v), Self::Null(_)) => v.is_nan(),
3270 (Self::Null(_), Self::Null(_)) => true,
3277 _ if self.is_missing() && other.is_missing() => true,
3304 (Self::Interval(a), Self::Interval(b)) => a == b && a.subtype == b.subtype,
3309 _ => self == other,
3310 }
3311 }
3312
3313 #[must_use]
3314 pub fn semantic_le(&self, other: &Self) -> bool {
3315 match self.semantic_cmp(other) {
3316 std::cmp::Ordering::Less | std::cmp::Ordering::Equal => true,
3317 std::cmp::Ordering::Greater => false,
3318 }
3319 }
3320
3321 #[must_use]
3322 pub fn semantic_ge(&self, other: &Self) -> bool {
3323 match self.semantic_cmp(other) {
3324 std::cmp::Ordering::Greater | std::cmp::Ordering::Equal => true,
3325 std::cmp::Ordering::Less => false,
3326 }
3327 }
3328
3329 #[must_use]
3330 pub fn is_null(&self) -> bool {
3331 matches!(self, Self::Null(_))
3332 }
3333
3334 #[must_use]
3335 pub fn is_na(&self) -> bool {
3336 self.is_missing()
3337 }
3338
3339 #[must_use]
3341 pub fn isna(&self) -> bool {
3342 self.is_missing()
3343 }
3344
3345 #[must_use]
3347 pub fn isnull(&self) -> bool {
3348 self.is_null()
3349 }
3350
3351 #[must_use]
3353 pub fn notna(&self) -> bool {
3354 !self.is_missing()
3355 }
3356
3357 #[must_use]
3359 pub fn notnull(&self) -> bool {
3360 !self.is_missing()
3361 }
3362
3363 #[must_use]
3365 pub fn is_not_na(&self) -> bool {
3366 !self.is_missing()
3367 }
3368
3369 #[must_use]
3371 pub fn not_na(&self) -> bool {
3372 !self.is_missing()
3373 }
3374
3375 #[must_use]
3376 pub fn coalesce(&self, other: &Self) -> Self {
3377 if self.is_missing() {
3378 other.clone()
3379 } else {
3380 self.clone()
3381 }
3382 }
3383
3384 #[must_use]
3385 pub fn semantic_cmp(&self, other: &Self) -> std::cmp::Ordering {
3386 match (self, other) {
3387 (Self::Int64(a), Self::Int64(b)) => a.cmp(b),
3388 (Self::Float64(a), Self::Float64(b)) => {
3389 a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)
3390 }
3391 (Self::Utf8(a), Self::Utf8(b)) => a.cmp(b),
3392 (Self::Bool(a), Self::Bool(b)) => a.cmp(b),
3393 (Self::Null(a), Self::Null(b)) => a.cmp(b),
3394 (Self::Timedelta64(a), Self::Timedelta64(b)) => {
3395 if *a == Timedelta::NAT || *b == Timedelta::NAT {
3396 std::cmp::Ordering::Equal
3397 } else {
3398 a.cmp(b)
3399 }
3400 }
3401 (Self::Datetime64(a), Self::Datetime64(b)) => {
3402 if *a == Timestamp::NAT || *b == Timestamp::NAT {
3403 std::cmp::Ordering::Equal
3404 } else {
3405 a.cmp(b)
3406 }
3407 }
3408 (Self::Period(a), Self::Period(b)) => {
3409 if a.ordinal == i64::MIN || b.ordinal == i64::MIN {
3410 std::cmp::Ordering::Equal
3411 } else {
3412 a.ordinal.cmp(&b.ordinal)
3413 }
3414 }
3415 (Self::Interval(a), Self::Interval(b)) => a
3416 .left
3417 .partial_cmp(&b.left)
3418 .unwrap_or(std::cmp::Ordering::Equal)
3419 .then_with(|| {
3420 a.right
3421 .partial_cmp(&b.right)
3422 .unwrap_or(std::cmp::Ordering::Equal)
3423 })
3424 .then_with(|| a.closed.cmp(&b.closed)),
3425 (Self::Object(a), Self::Object(b)) => a.cmp(b),
3427 (Self::Int64(a), Self::Float64(b)) => (*a as f64)
3429 .partial_cmp(b)
3430 .unwrap_or(std::cmp::Ordering::Equal),
3431 (Self::Float64(a), Self::Int64(b)) => a
3432 .partial_cmp(&(*b as f64))
3433 .unwrap_or(std::cmp::Ordering::Equal),
3434 (a, b) => a.debug_variant_name().cmp(b.debug_variant_name()),
3438 }
3439 }
3440
3441 pub fn to_f64(&self) -> Result<f64, TypeError> {
3442 match self {
3443 Self::Bool(v) => Ok(if *v { 1.0 } else { 0.0 }),
3444 Self::Int64(v) => Ok(*v as f64),
3445 Self::Float64(v) => Ok(*v),
3446 Self::Null(kind) => Err(TypeError::ValueIsMissing { kind: *kind }),
3447 Self::Utf8(v) => Err(TypeError::NonNumericValue {
3448 value: v.clone(),
3449 dtype: DType::Utf8,
3450 }),
3451 Self::Timedelta64(v) if *v == Timedelta::NAT => Err(TypeError::ValueIsMissing {
3452 kind: NullKind::NaT,
3453 }),
3454 Self::Timedelta64(v) => Err(TypeError::NonNumericValue {
3455 value: Timedelta::format(*v),
3456 dtype: DType::Timedelta64,
3457 }),
3458 Self::Datetime64(v) if *v == Timestamp::NAT => Err(TypeError::ValueIsMissing {
3459 kind: NullKind::NaT,
3460 }),
3461 Self::Datetime64(v) => Err(TypeError::NonNumericValue {
3462 value: format!("Timestamp[{v}]"),
3463 dtype: DType::datetime64_naive(),
3464 }),
3465 Self::Period(p) if p.ordinal == i64::MIN => Err(TypeError::ValueIsMissing {
3466 kind: NullKind::NaT,
3467 }),
3468 Self::Period(p) => Err(TypeError::NonNumericValue {
3469 value: p.calendar_string(),
3470 dtype: DType::Period,
3471 }),
3472 Self::Interval(v) => Err(TypeError::NonNumericValue {
3473 value: v.to_string(),
3474 dtype: DType::Interval,
3475 }),
3476 Self::Object(object) => Err(TypeError::NonNumericValue {
3477 value: object.repr(),
3478 dtype: DType::Utf8,
3479 }),
3480 }
3481 }
3482
3483 pub fn to_i64(&self) -> Result<i64, TypeError> {
3485 match self {
3486 Self::Bool(v) => Ok(if *v { 1 } else { 0 }),
3487 Self::Int64(v) => Ok(*v),
3488 Self::Float64(v) => Ok(*v as i64),
3489 Self::Null(kind) => Err(TypeError::ValueIsMissing { kind: *kind }),
3490 Self::Utf8(v) => Err(TypeError::NonNumericValue {
3491 value: v.clone(),
3492 dtype: DType::Utf8,
3493 }),
3494 Self::Timedelta64(v) if *v == Timedelta::NAT => Err(TypeError::ValueIsMissing {
3495 kind: NullKind::NaT,
3496 }),
3497 Self::Timedelta64(v) => Ok(*v),
3498 Self::Datetime64(v) if *v == Timestamp::NAT => Err(TypeError::ValueIsMissing {
3499 kind: NullKind::NaT,
3500 }),
3501 Self::Datetime64(v) => Ok(*v),
3502 Self::Period(p) if p.ordinal == i64::MIN => Err(TypeError::ValueIsMissing {
3503 kind: NullKind::NaT,
3504 }),
3505 Self::Period(p) => Ok(p.ordinal),
3506 Self::Interval(v) => Err(TypeError::NonNumericValue {
3507 value: v.to_string(),
3508 dtype: DType::Interval,
3509 }),
3510 Self::Object(object) => Err(TypeError::NonNumericValue {
3511 value: object.repr(),
3512 dtype: DType::Utf8,
3513 }),
3514 }
3515 }
3516
3517 pub fn to_bool(&self) -> Result<bool, TypeError> {
3519 match self {
3520 Self::Bool(v) => Ok(*v),
3521 Self::Int64(v) => Ok(*v != 0),
3522 Self::Float64(v) => Ok(*v != 0.0 && !v.is_nan()),
3523 Self::Null(kind) => Err(TypeError::ValueIsMissing { kind: *kind }),
3524 Self::Utf8(v) => Ok(!v.is_empty()),
3525 Self::Timedelta64(v) if *v == Timedelta::NAT => Err(TypeError::ValueIsMissing {
3526 kind: NullKind::NaT,
3527 }),
3528 Self::Timedelta64(v) => Ok(*v != 0),
3529 Self::Datetime64(v) if *v == Timestamp::NAT => Err(TypeError::ValueIsMissing {
3530 kind: NullKind::NaT,
3531 }),
3532 Self::Datetime64(v) => Ok(*v != 0),
3533 Self::Period(p) if p.ordinal == i64::MIN => Err(TypeError::ValueIsMissing {
3534 kind: NullKind::NaT,
3535 }),
3536 Self::Period(p) => Ok(p.ordinal != 0),
3537 Self::Interval(_) => Ok(true),
3538 Self::Object(ObjectValue::List(items)) => Ok(!items.is_empty()),
3541 Self::Object(ObjectValue::Bytes(data)) => Ok(!data.is_empty()),
3542 Self::Object(ObjectValue::Host(_)) => Ok(true),
3543 }
3544 }
3545
3546 pub fn to_str(&self) -> String {
3548 match self {
3549 Self::Bool(v) => if *v { "True" } else { "False" }.to_string(),
3550 Self::Int64(v) => v.to_string(),
3551 Self::Float64(v) => {
3552 if v.is_nan() {
3553 "nan".to_string()
3554 } else if v.is_infinite() {
3555 if *v > 0.0 { "inf" } else { "-inf" }.to_string()
3556 } else {
3557 v.to_string()
3558 }
3559 }
3560 Self::Null(_) => "NaN".to_string(),
3561 Self::Utf8(v) => v.clone(),
3562 Self::Timedelta64(v) => Timedelta::format(*v),
3563 Self::Datetime64(v) if *v == Timestamp::NAT => "NaT".to_string(),
3564 Self::Datetime64(v) => Timestamp::from_nanos(*v).isoformat(),
3565 Self::Period(p) if p.ordinal == i64::MIN => "NaT".to_string(),
3566 Self::Period(p) => p.calendar_string(),
3567 Self::Interval(v) => v.to_string(),
3568 Self::Object(object) => object.to_string(),
3569 }
3570 }
3571}
3572
3573#[derive(Debug, Error, Clone, PartialEq)]
3574pub enum TypeError {
3575 #[error("dtype coercion from {left:?} to {right:?} has no compatible common type")]
3576 IncompatibleDtypes { left: DType, right: DType },
3577 #[error("cannot cast scalar of dtype {from:?} to {to:?}")]
3578 InvalidCast { from: DType, to: DType },
3579 #[error("cannot cast float {value} to int64 without loss")]
3580 LossyFloatToInt { value: f64 },
3581 #[error("expected 0/1 for bool cast from int64 but found {value}")]
3582 InvalidBoolInt { value: i64 },
3583 #[error("expected 0.0/1.0 for bool cast from float64 but found {value}")]
3584 InvalidBoolFloat { value: f64 },
3585 #[error("value {value:?} has non-numeric dtype {dtype:?}")]
3586 NonNumericValue { value: String, dtype: DType },
3587 #[error("value is missing ({kind:?})")]
3588 ValueIsMissing { kind: NullKind },
3589 #[error("sparse value dtype cannot be {dtype:?}")]
3590 InvalidSparseValueDType { dtype: DType },
3591 #[error("interval_range step must be finite, positive, and not NaN (got {step})")]
3592 InvalidIntervalStep { step: f64 },
3593 #[error("interval_range step {step} does not evenly divide range end-start={span}")]
3594 IntervalStepDoesNotDivide { step: f64, span: f64 },
3595 #[error("interval_range requires exactly 3 of (start, end, periods, freq) to be specified")]
3596 IntervalRangeParameterCount,
3597 #[error("cannot parse '{value}' as {target}")]
3598 ValueNotParseable { value: String, target: String },
3599}
3600
3601pub fn common_dtype(left: DType, right: DType) -> Result<DType, TypeError> {
3602 use DType::{
3603 Bool, BoolNullable, Categorical, Float64, Float64Nullable, Int64, Int64Nullable, Null,
3604 Sparse, Timedelta64,
3605 };
3606
3607 let out = match (&left, &right) {
3608 (a, b) if a == b => a.clone(),
3609 (Null, other) | (other, Null) => other.clone(),
3610 (Categorical, Categorical) => Categorical,
3611
3612 (Bool, Int64) | (Int64, Bool) => Int64,
3614 (Bool, Int64Nullable) | (Int64Nullable, Bool) => Int64Nullable,
3615 (BoolNullable, Int64) | (Int64, BoolNullable) => Int64Nullable,
3616 (BoolNullable, Int64Nullable) | (Int64Nullable, BoolNullable) => Int64Nullable,
3617 (Bool, BoolNullable) | (BoolNullable, Bool) => BoolNullable,
3618 (Bool, Float64) | (Float64, Bool) => Float64,
3619 (BoolNullable, Float64) | (Float64, BoolNullable) => Float64Nullable,
3625
3626 (Int64, Float64) | (Float64, Int64) => Float64,
3628 (Int64Nullable, Float64) | (Float64, Int64Nullable) => Float64Nullable,
3642 (Int64, Int64Nullable) | (Int64Nullable, Int64) => Int64Nullable,
3643
3644 (Float64Nullable, Float64) | (Float64, Float64Nullable) => Float64Nullable,
3661 (Float64Nullable, Int64) | (Int64, Float64Nullable) => Float64Nullable,
3662 (Float64Nullable, Int64Nullable) | (Int64Nullable, Float64Nullable) => Float64Nullable,
3663 (Float64Nullable, Bool) | (Bool, Float64Nullable) => Float64Nullable,
3664 (Float64Nullable, BoolNullable) | (BoolNullable, Float64Nullable) => Float64Nullable,
3665
3666 (Timedelta64, Timedelta64) => Timedelta64,
3668 (DType::Datetime64 { tz: left_tz }, DType::Datetime64 { tz: right_tz })
3669 if left_tz == right_tz =>
3670 {
3671 DType::Datetime64 {
3672 tz: left_tz.clone(),
3673 }
3674 }
3675
3676 (Sparse, _) | (_, Sparse) => {
3677 return Err(TypeError::IncompatibleDtypes {
3678 left: left.clone(),
3679 right: right.clone(),
3680 });
3681 }
3682 _ => {
3683 return Err(TypeError::IncompatibleDtypes { left, right });
3684 }
3685 };
3686
3687 Ok(out)
3688}
3689
3690pub fn infer_dtype(values: &[Scalar]) -> Result<DType, TypeError> {
3691 let mut current = DType::Null;
3692 let mut saw_utf8 = false;
3693 let mut saw_timedelta = false;
3694 let mut saw_datetime = false;
3695 let mut saw_non_utf8_non_null = false;
3696 let mut saw_bool = false;
3703 let mut saw_numeric = false;
3704 let mut period_freq: Option<PeriodFreq> = None;
3709
3710 for value in values {
3724 if let Scalar::Period(period) = value
3725 && period.ordinal != i64::MIN
3726 {
3727 match period_freq {
3728 None => period_freq = Some(period.freq),
3729 Some(freq) if freq != period.freq => {
3730 return Err(TypeError::IncompatibleDtypes {
3731 left: DType::Period,
3732 right: DType::Period,
3733 });
3734 }
3735 Some(_) => {}
3736 }
3737 }
3738 match value.dtype() {
3739 DType::Null => {}
3740 DType::Utf8 => saw_utf8 = true,
3741 DType::Bool => {
3742 saw_bool = true;
3743 saw_non_utf8_non_null = true;
3744 current = common_dtype(current, DType::Bool)?;
3745 }
3746 DType::Int64 | DType::Float64 => {
3747 saw_numeric = true;
3748 saw_non_utf8_non_null = true;
3749 current = common_dtype(current, value.dtype())?;
3750 }
3751 DType::Timedelta64 => {
3752 saw_timedelta = true;
3753 if current == DType::Null {
3754 current = DType::Timedelta64;
3755 } else if current != DType::Timedelta64 {
3756 return Err(TypeError::IncompatibleDtypes {
3757 left: current,
3758 right: DType::Timedelta64,
3759 });
3760 }
3761 }
3762 DType::Datetime64 { .. } => {
3763 saw_datetime = true;
3764 if current == DType::Null {
3765 current = DType::datetime64_naive();
3766 } else if !current.is_datetime() {
3767 return Err(TypeError::IncompatibleDtypes {
3768 left: current,
3769 right: DType::datetime64_naive(),
3770 });
3771 }
3772 }
3773 other => {
3774 saw_non_utf8_non_null = true;
3775 current = common_dtype(current, other)?;
3776 }
3777 }
3778
3779 if saw_bool && saw_numeric {
3780 return Ok(DType::Utf8);
3784 }
3785 if saw_utf8 && saw_non_utf8_non_null {
3786 return Ok(DType::Utf8);
3790 }
3791 if saw_timedelta && saw_non_utf8_non_null {
3792 return Err(TypeError::IncompatibleDtypes {
3793 left: DType::Timedelta64,
3794 right: current,
3795 });
3796 }
3797 if saw_datetime && saw_non_utf8_non_null {
3798 return Err(TypeError::IncompatibleDtypes {
3799 left: DType::datetime64_naive(),
3800 right: current,
3801 });
3802 }
3803 }
3804
3805 if saw_utf8 {
3806 Ok(DType::Utf8)
3807 } else {
3808 Ok(current)
3809 }
3810}
3811
3812pub fn cast_scalar_owned(value: Scalar, target: DType) -> Result<Scalar, TypeError> {
3815 let from = value.dtype();
3816 if from == target {
3817 return Ok(value);
3818 }
3819 if (from == DType::Int64 && target == DType::Int64Nullable)
3821 || (from == DType::Int64Nullable && target == DType::Int64)
3822 {
3823 return Ok(value);
3824 }
3825 if (from == DType::Bool && target == DType::BoolNullable)
3827 || (from == DType::BoolNullable && target == DType::Bool)
3828 {
3829 return Ok(value);
3830 }
3831 if (from == DType::Float64 && target == DType::Float64Nullable)
3839 || (from == DType::Float64Nullable && target == DType::Float64)
3840 {
3841 return Ok(value);
3842 }
3843 if from.is_datetime() && target.is_datetime() {
3847 return Ok(value);
3848 }
3849 if target == DType::Utf8 {
3850 return Ok(Scalar::Utf8(scalar_to_string_for_astype(value)));
3851 }
3852 if target == DType::Bool
3858 && let Scalar::Float64(v) = &value
3859 && v.is_nan()
3860 {
3861 return Ok(Scalar::Bool(true));
3862 }
3863 if target == DType::Bool {
3889 match &value {
3890 Scalar::Datetime64(nanos) | Scalar::Timedelta64(nanos) => {
3891 return Ok(Scalar::Bool(*nanos != 0));
3892 }
3893 _ => {}
3894 }
3895 }
3896 if target == DType::Int64 {
3921 match &value {
3922 Scalar::Datetime64(nanos) | Scalar::Timedelta64(nanos) => {
3923 return Ok(Scalar::Int64(*nanos));
3924 }
3925 _ => {}
3926 }
3927 }
3928 if value.is_missing() {
3929 return Ok(Scalar::missing_for_dtype(target));
3930 }
3931
3932 match target {
3935 DType::Null => Ok(Scalar::Null(NullKind::Null)),
3936 DType::Bool => match &value {
3937 Scalar::Int64(v) => Ok(Scalar::Bool(*v != 0)),
3940 Scalar::Float64(v) => Ok(Scalar::Bool(*v != 0.0)),
3943 _ => Err(TypeError::InvalidCast { from, to: target }),
3944 },
3945 DType::BoolNullable => match &value {
3946 Scalar::Bool(b) => Ok(Scalar::Bool(*b)),
3951 Scalar::Int64(0) => Ok(Scalar::Bool(false)),
3952 Scalar::Int64(1) => Ok(Scalar::Bool(true)),
3953 Scalar::Int64(v) => Err(TypeError::InvalidBoolInt { value: *v }),
3954 Scalar::Float64(v) if *v == 0.0 => Ok(Scalar::Bool(false)),
3955 Scalar::Float64(v) if *v == 1.0 => Ok(Scalar::Bool(true)),
3956 Scalar::Float64(v) => Err(TypeError::InvalidBoolFloat { value: *v }),
3957 _ => Err(TypeError::InvalidCast { from, to: target }),
3958 },
3959 DType::Int64 | DType::Int64Nullable => match &value {
3960 Scalar::Bool(v) => Ok(Scalar::Int64(i64::from(*v))),
3961 Scalar::Float64(v) => {
3962 if !v.is_finite() {
3969 return Err(TypeError::LossyFloatToInt { value: *v });
3970 }
3971 if *v < i64::MIN as f64 || *v >= 9223372036854775808.0 {
3972 return Err(TypeError::LossyFloatToInt { value: *v });
3973 }
3974 Ok(Scalar::Int64(*v as i64))
3975 }
3976 Scalar::Utf8(s) => {
3977 if let Ok(v) = s.parse::<i64>() {
3980 return Ok(Scalar::Int64(v));
3981 }
3982 if let Ok(f) = s.parse::<f64>()
3983 && f.is_finite()
3984 && f.fract() == 0.0
3985 && f >= i64::MIN as f64
3986 && f < 9223372036854775808.0
3987 {
3988 return Ok(Scalar::Int64(f as i64));
3989 }
3990 Err(TypeError::InvalidCast { from, to: target })
3991 }
3992 _ => Err(TypeError::InvalidCast { from, to: target }),
3993 },
3994 DType::Float64 | DType::Float64Nullable => match &value {
3998 Scalar::Bool(v) => Ok(Scalar::Float64(if *v { 1.0 } else { 0.0 })),
3999 Scalar::Int64(v) => Ok(Scalar::Float64(*v as f64)),
4000 Scalar::Utf8(s) => s
4001 .parse::<f64>()
4002 .map(Scalar::Float64)
4003 .map_err(|_| TypeError::InvalidCast { from, to: target }),
4004 _ => Err(TypeError::InvalidCast { from, to: target }),
4005 },
4006 DType::Utf8 => Ok(Scalar::Utf8(scalar_to_string_for_astype(value))),
4007 DType::Categorical => Err(TypeError::InvalidCast { from, to: target }),
4008 DType::Timedelta64 => match &value {
4009 Scalar::Bool(v) => Ok(Scalar::Timedelta64(i64::from(*v))),
4020 Scalar::Int64(v) => Ok(Scalar::Timedelta64(*v)),
4021 Scalar::Float64(v) => Ok(Scalar::Timedelta64(float_to_temporal_nanos(*v))),
4022 Scalar::Utf8(s) => Timedelta::parse(s)
4023 .map(Scalar::Timedelta64)
4024 .map_err(|_| TypeError::InvalidCast { from, to: target }),
4025 _ => Err(TypeError::InvalidCast { from, to: target }),
4026 },
4027 DType::Datetime64 { .. } => match &value {
4028 Scalar::Bool(v) => Ok(Scalar::Datetime64(i64::from(*v))),
4031 Scalar::Int64(v) => Ok(Scalar::Datetime64(*v)),
4032 Scalar::Float64(v) => Ok(Scalar::Datetime64(float_to_temporal_nanos(*v))),
4033 Scalar::Utf8(s) => Timestamp::parse(s)
4034 .map(|timestamp| Scalar::Datetime64(timestamp.nanos))
4035 .map_err(|_| TypeError::InvalidCast { from, to: target }),
4036 _ => Err(TypeError::InvalidCast { from, to: target }),
4037 },
4038 DType::Period => match &value {
4039 Scalar::Int64(v) => Ok(Scalar::Period(Period::new(*v, PeriodFreq::Daily))),
4042 Scalar::Utf8(s) => Period::parse(s)
4043 .map(Scalar::Period)
4044 .map_err(|_| TypeError::InvalidCast { from, to: target }),
4045 _ => Err(TypeError::InvalidCast { from, to: target }),
4046 },
4047 DType::Interval => match &value {
4048 Scalar::Utf8(s) => Interval::parse(s)
4049 .map(Scalar::Interval)
4050 .map_err(|_| TypeError::InvalidCast { from, to: target }),
4051 _ => Err(TypeError::InvalidCast { from, to: target }),
4052 },
4053 DType::Sparse => Err(TypeError::InvalidCast { from, to: target }),
4054 }
4055}
4056
4057fn float_to_temporal_nanos(value: f64) -> i64 {
4093 if value.is_finite() && value > (i64::MIN as f64) && value < (i64::MAX as f64) {
4096 value as i64
4098 } else {
4099 Timestamp::NAT
4102 }
4103}
4104
4105fn scalar_to_string_for_astype(value: Scalar) -> String {
4106 match value {
4107 Scalar::Null(NullKind::Null) => "None".to_owned(),
4108 Scalar::Null(NullKind::NaN) => "nan".to_owned(),
4109 Scalar::Null(NullKind::NaT) => "NaT".to_owned(),
4110 Scalar::Bool(true) => "True".to_owned(),
4111 Scalar::Bool(false) => "False".to_owned(),
4112 Scalar::Int64(v) => v.to_string(),
4113 Scalar::Float64(v) => float_to_string_for_astype(v),
4114 Scalar::Utf8(s) => s,
4115 Scalar::Timedelta64(v) if v == Timedelta::NAT => "NaT".to_owned(),
4116 Scalar::Timedelta64(v) => Timedelta::format(v),
4117 Scalar::Datetime64(v) if v == Timestamp::NAT => "NaT".to_owned(),
4118 Scalar::Datetime64(v) => timestamp_text(v),
4119 Scalar::Period(p) if p.ordinal == i64::MIN => "NaT".to_owned(),
4120 Scalar::Period(p) => p.calendar_string(),
4121 Scalar::Interval(v) => v.to_string(),
4122 Scalar::Object(object) => object.to_string(),
4124 }
4125}
4126
4127pub fn float_to_string_for_astype(value: f64) -> String {
4128 use std::fmt::Write as _;
4129
4130 if value.is_nan() {
4131 return "nan".to_owned();
4132 }
4133 if value.is_infinite() {
4134 return value.to_string(); }
4136 let mut rendered = String::with_capacity(32);
4148 let _ = write!(rendered, "{value:?}");
4149 let Some(exponent_marker) = rendered.find('e') else {
4150 return rendered;
4151 };
4152
4153 let sign_position = exponent_marker + 1;
4154 let digits_position = match rendered.as_bytes().get(sign_position) {
4155 Some(b'+' | b'-') => sign_position + 1,
4156 _ => {
4157 rendered.insert(sign_position, '+');
4158 sign_position + 1
4159 }
4160 };
4161 if rendered.len() - digits_position == 1 {
4162 rendered.insert(digits_position, '0');
4163 }
4164 rendered
4165}
4166
4167static ENG_FLOAT_ACCURACY: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(3);
4168static ENG_FLOAT_USE_PREFIX: std::sync::atomic::AtomicBool =
4169 std::sync::atomic::AtomicBool::new(false);
4170static ENG_FLOAT_ACTIVE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
4171
4172pub fn eng_float_format(num: f64, accuracy: Option<usize>, use_eng_prefix: bool) -> String {
4174 if num.is_nan() {
4175 return "NaN".to_string();
4176 }
4177 if num.is_infinite() {
4178 return if num < 0.0 {
4179 "-inf".to_string()
4180 } else {
4181 "inf".to_string()
4182 };
4183 }
4184
4185 let sign = if num < 0.0 { -1.0 } else { 1.0 };
4186 let abs_num = num.abs();
4187
4188 let pow10 = if abs_num != 0.0 {
4189 let p = (abs_num.log10() / 3.0).floor() as i32 * 3;
4190 p.clamp(-24, 24)
4191 } else {
4192 0
4193 };
4194
4195 let prefix = if use_eng_prefix {
4196 match pow10 {
4197 -24 => "y",
4198 -21 => "z",
4199 -18 => "a",
4200 -15 => "f",
4201 -12 => "p",
4202 -9 => "n",
4203 -6 => "u",
4204 -3 => "m",
4205 0 => "",
4206 3 => "k",
4207 6 => "M",
4208 9 => "G",
4209 12 => "T",
4210 15 => "P",
4211 18 => "E",
4212 21 => "Z",
4213 24 => "Y",
4214 _ => "",
4215 }
4216 .to_string()
4217 } else if pow10 < 0 {
4218 format!("E-{:02}", -pow10)
4219 } else {
4220 format!("E+{:02}", pow10)
4221 };
4222
4223 let mant = (sign * abs_num) / 10f64.powi(pow10);
4224
4225 if let Some(acc) = accuracy {
4226 format!("{mant:.acc$}{prefix}", acc = acc)
4227 } else {
4228 format!("{mant}{prefix}")
4229 }
4230}
4231
4232pub fn set_eng_float_format(accuracy: usize, use_eng_prefix: bool) {
4235 use std::sync::atomic::Ordering;
4236 ENG_FLOAT_ACCURACY.store(accuracy, Ordering::Relaxed);
4237 ENG_FLOAT_USE_PREFIX.store(use_eng_prefix, Ordering::Relaxed);
4238 ENG_FLOAT_ACTIVE.store(true, Ordering::Relaxed);
4239}
4240
4241pub fn reset_eng_float_format() {
4243 use std::sync::atomic::Ordering;
4244 ENG_FLOAT_ACTIVE.store(false, Ordering::Relaxed);
4245}
4246
4247pub fn get_eng_float_format() -> Option<(usize, bool)> {
4249 use std::sync::atomic::Ordering;
4250 if ENG_FLOAT_ACTIVE.load(Ordering::Relaxed) {
4251 Some((
4252 ENG_FLOAT_ACCURACY.load(Ordering::Relaxed),
4253 ENG_FLOAT_USE_PREFIX.load(Ordering::Relaxed),
4254 ))
4255 } else {
4256 None
4257 }
4258}
4259
4260#[derive(Debug, Error, Clone, PartialEq, Eq)]
4264pub enum OptionError {
4265 #[error("no such option: '{pat}'")]
4266 NotFound { pat: String },
4267 #[error("option pattern '{pat}' matches multiple options: {matches:?}")]
4268 Ambiguous { pat: String, matches: Vec<String> },
4269 #[error("invalid option value for '{pat}': {reason}")]
4270 InvalidValue { pat: String, reason: String },
4271}
4272
4273#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
4275pub enum OptionValue {
4276 None,
4277 Int(i64),
4278 Float(f64),
4279 Bool(bool),
4280 Str(String),
4281}
4282
4283impl OptionValue {
4284 #[must_use]
4285 pub const fn is_none(&self) -> bool {
4286 matches!(self, Self::None)
4287 }
4288
4289 #[must_use]
4290 pub const fn as_int(&self) -> Option<i64> {
4291 match self {
4292 Self::Int(i) => Some(*i),
4293 _ => None,
4294 }
4295 }
4296
4297 #[must_use]
4298 pub const fn as_float(&self) -> Option<f64> {
4299 match self {
4300 Self::Float(f) => Some(*f),
4301 _ => None,
4302 }
4303 }
4304
4305 #[must_use]
4306 pub const fn as_bool(&self) -> Option<bool> {
4307 match self {
4308 Self::Bool(b) => Some(*b),
4309 _ => None,
4310 }
4311 }
4312
4313 #[must_use]
4314 pub fn as_str(&self) -> Option<&str> {
4315 match self {
4316 Self::Str(s) => Some(s.as_str()),
4317 _ => None,
4318 }
4319 }
4320}
4321
4322impl std::fmt::Display for OptionValue {
4323 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4324 match self {
4325 Self::None => write!(f, "None"),
4326 Self::Int(i) => write!(f, "{i}"),
4327 Self::Float(fl) => write!(f, "{fl}"),
4328 Self::Bool(b) => write!(f, "{b}"),
4329 Self::Str(s) => write!(f, "{s}"),
4330 }
4331 }
4332}
4333
4334impl From<i64> for OptionValue {
4335 fn from(v: i64) -> Self {
4336 Self::Int(v)
4337 }
4338}
4339
4340impl From<i32> for OptionValue {
4341 fn from(v: i32) -> Self {
4342 Self::Int(i64::from(v))
4343 }
4344}
4345
4346impl From<usize> for OptionValue {
4347 fn from(v: usize) -> Self {
4348 Self::Int(i64::try_from(v).unwrap_or(i64::MAX))
4349 }
4350}
4351
4352impl From<f64> for OptionValue {
4353 fn from(v: f64) -> Self {
4354 Self::Float(v)
4355 }
4356}
4357
4358impl From<bool> for OptionValue {
4359 fn from(v: bool) -> Self {
4360 Self::Bool(v)
4361 }
4362}
4363
4364impl From<&str> for OptionValue {
4365 fn from(v: &str) -> Self {
4366 Self::Str(v.to_string())
4367 }
4368}
4369
4370impl From<String> for OptionValue {
4371 fn from(v: String) -> Self {
4372 Self::Str(v)
4373 }
4374}
4375
4376impl From<()> for OptionValue {
4377 fn from(_: ()) -> Self {
4378 Self::None
4379 }
4380}
4381
4382fn default_options_map() -> std::collections::BTreeMap<String, OptionValue> {
4383 let mut m = std::collections::BTreeMap::new();
4384 m.insert("display.max_rows".to_string(), OptionValue::Int(60));
4385 m.insert("display.min_rows".to_string(), OptionValue::Int(10));
4386 m.insert("display.max_columns".to_string(), OptionValue::Int(0));
4387 m.insert("display.width".to_string(), OptionValue::Int(80));
4388 m.insert("display.precision".to_string(), OptionValue::Int(6));
4389 m.insert("display.max_colwidth".to_string(), OptionValue::Int(50));
4390 m.insert(
4391 "display.show_dimensions".to_string(),
4392 OptionValue::Bool(true),
4393 );
4394 m.insert("display.float_format".to_string(), OptionValue::None);
4395 m.insert(
4396 "display.large_repr".to_string(),
4397 OptionValue::Str("truncate".to_string()),
4398 );
4399 m.insert(
4400 "display.max_info_columns".to_string(),
4401 OptionValue::Int(100),
4402 );
4403 m.insert(
4404 "display.max_info_rows".to_string(),
4405 OptionValue::Int(1690785),
4406 );
4407 m.insert("display.memory_usage".to_string(), OptionValue::Bool(true));
4408 m.insert(
4409 "display.colheader_justify".to_string(),
4410 OptionValue::Str("right".to_string()),
4411 );
4412 m.insert("display.chop_threshold".to_string(), OptionValue::None);
4413 m.insert(
4414 "display.date_dayfirst".to_string(),
4415 OptionValue::Bool(false),
4416 );
4417 m.insert(
4418 "display.date_yearfirst".to_string(),
4419 OptionValue::Bool(false),
4420 );
4421 m.insert(
4422 "display.encoding".to_string(),
4423 OptionValue::Str("utf-8".to_string()),
4424 );
4425 m.insert("mode.sim_interactive".to_string(), OptionValue::Bool(false));
4426 m.insert(
4427 "mode.chained_assignment".to_string(),
4428 OptionValue::Str("warn".to_string()),
4429 );
4430 m.insert("mode.use_inf_as_na".to_string(), OptionValue::Bool(false));
4431 m.insert("mode.copy_on_write".to_string(), OptionValue::Bool(false));
4432 m.insert(
4433 "mode.data_manager".to_string(),
4434 OptionValue::Str("block".to_string()),
4435 );
4436 m.insert(
4437 "compute.use_bottleneck".to_string(),
4438 OptionValue::Bool(true),
4439 );
4440 m.insert("compute.use_numba".to_string(), OptionValue::Bool(false));
4441 m.insert(
4442 "io.excel.zip.reader".to_string(),
4443 OptionValue::Str("zipfile".to_string()),
4444 );
4445 m.insert(
4446 "io.parquet.engine".to_string(),
4447 OptionValue::Str("auto".to_string()),
4448 );
4449 m.insert(
4450 "io.sql.engine".to_string(),
4451 OptionValue::Str("auto".to_string()),
4452 );
4453 m.insert(
4454 "plotting.backend".to_string(),
4455 OptionValue::Str("matplotlib".to_string()),
4456 );
4457 m.insert(
4458 "plotting.matplotlib.register_converters".to_string(),
4459 OptionValue::Bool(true),
4460 );
4461 m
4462}
4463
4464static GLOBAL_OPTIONS: std::sync::LazyLock<
4465 std::sync::Mutex<std::collections::BTreeMap<String, OptionValue>>,
4466> = std::sync::LazyLock::new(|| std::sync::Mutex::new(default_options_map()));
4467
4468fn resolve_option_key(
4469 pat: &str,
4470 map: &std::collections::BTreeMap<String, OptionValue>,
4471) -> Result<String, OptionError> {
4472 if map.contains_key(pat) {
4473 return Ok(pat.to_string());
4474 }
4475 let matches: Vec<String> = map
4476 .keys()
4477 .filter(|k| k.ends_with(pat) || k.contains(pat))
4478 .cloned()
4479 .collect();
4480 if matches.len() == 1 {
4481 Ok(matches[0].clone())
4482 } else if matches.is_empty() {
4483 Err(OptionError::NotFound {
4484 pat: pat.to_string(),
4485 })
4486 } else {
4487 Err(OptionError::Ambiguous {
4488 pat: pat.to_string(),
4489 matches,
4490 })
4491 }
4492}
4493
4494pub fn get_option(pat: &str) -> Result<OptionValue, OptionError> {
4500 let map = GLOBAL_OPTIONS
4501 .lock()
4502 .unwrap_or_else(std::sync::PoisonError::into_inner);
4503 let key = resolve_option_key(pat, &map)?;
4504 Ok(map.get(&key).cloned().unwrap_or(OptionValue::None))
4505}
4506
4507pub fn set_option(pat: &str, val: impl Into<OptionValue>) -> Result<(), OptionError> {
4513 let mut map = GLOBAL_OPTIONS
4514 .lock()
4515 .unwrap_or_else(std::sync::PoisonError::into_inner);
4516 let key = resolve_option_key(pat, &map)?;
4517 let v = val.into();
4518 map.insert(key, v);
4519 Ok(())
4520}
4521
4522pub fn reset_option(pat: Option<&str>) -> Result<(), OptionError> {
4529 let mut map = GLOBAL_OPTIONS
4530 .lock()
4531 .unwrap_or_else(std::sync::PoisonError::into_inner);
4532 let defaults = default_options_map();
4533 let p = pat.unwrap_or("all");
4534 if p == "all" {
4535 *map = defaults;
4536 return Ok(());
4537 }
4538 let key = resolve_option_key(p, &defaults)?;
4539 if let Some(def_val) = defaults.get(&key) {
4540 map.insert(key, def_val.clone());
4541 }
4542 Ok(())
4543}
4544
4545pub fn describe_option(pat: Option<&str>) -> Result<String, OptionError> {
4550 use std::fmt::Write as _;
4551 let map = GLOBAL_OPTIONS
4552 .lock()
4553 .unwrap_or_else(std::sync::PoisonError::into_inner);
4554 let mut out = String::with_capacity(map.len() * 40);
4555 let mut matched = 0;
4556 for (k, v) in map.iter() {
4557 if let Some(p) = pat
4558 && !k.contains(p)
4559 {
4560 continue;
4561 }
4562 if matched > 0 {
4563 out.push('\n');
4564 }
4565 let _ = write!(out, "{k} : [currently: {v}]");
4566 matched += 1;
4567 }
4568 if matched == 0
4569 && let Some(p) = pat
4570 {
4571 return Err(OptionError::NotFound { pat: p.to_string() });
4572 }
4573 Ok(out)
4574}
4575
4576#[derive(Debug)]
4578pub struct OptionContextGuard {
4579 saved: Vec<(String, OptionValue)>,
4580}
4581
4582impl Drop for OptionContextGuard {
4583 fn drop(&mut self) {
4584 let mut map = GLOBAL_OPTIONS
4585 .lock()
4586 .unwrap_or_else(std::sync::PoisonError::into_inner);
4587 for (k, old) in self.saved.drain(..) {
4588 map.insert(k, old);
4589 }
4590 }
4591}
4592
4593pub fn option_context(entries: &[(&str, OptionValue)]) -> Result<OptionContextGuard, OptionError> {
4598 let mut map = GLOBAL_OPTIONS
4599 .lock()
4600 .unwrap_or_else(std::sync::PoisonError::into_inner);
4601 let mut saved = Vec::with_capacity(entries.len());
4602 for (pat, new_val) in entries {
4603 let key = resolve_option_key(pat, &map)?;
4604 if let Some(old) = map.get(&key) {
4605 saved.push((key.clone(), old.clone()));
4606 }
4607 map.insert(key, new_val.clone());
4608 }
4609 Ok(OptionContextGuard { saved })
4610}
4611
4612pub fn cast_scalar(value: &Scalar, target: DType) -> Result<Scalar, TypeError> {
4614 cast_scalar_owned(value.clone(), target)
4615}
4616
4617#[derive(Debug, Error, Clone, PartialEq)]
4620pub enum TimedeltaError {
4621 #[error("invalid timedelta string: {0}")]
4622 InvalidFormat(String),
4623 #[error("overflow in timedelta computation")]
4624 Overflow,
4625}
4626
4627impl TimedeltaError {
4628 #[must_use]
4634 pub const fn pandas_error(&self) -> Option<PandasTemporalError> {
4635 match self {
4636 Self::Overflow => Some(PandasTemporalError::OutOfBoundsTimedelta),
4639 Self::InvalidFormat(_) => None,
4640 }
4641 }
4642}
4643
4644#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
4645pub struct CategoricalMetadata {
4646 pub categories: Vec<Scalar>,
4648 pub ordered: bool,
4650}
4651
4652impl CategoricalMetadata {
4653 #[must_use]
4654 pub fn new(categories: Vec<Scalar>, ordered: bool) -> Self {
4655 Self {
4656 categories,
4657 ordered,
4658 }
4659 }
4660}
4661
4662#[derive(Debug, Clone, Copy, Default)]
4663pub struct TimedeltaComponents {
4664 pub days: i64,
4665 pub hours: i64,
4666 pub minutes: i64,
4667 pub seconds: i64,
4668 pub milliseconds: i64,
4669 pub microseconds: i64,
4670 pub nanoseconds: i64,
4671}
4672
4673#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4685pub enum PandasTemporalError {
4686 Overflow,
4690 OutOfBoundsDatetime,
4693 OutOfBoundsTimedelta,
4698 OverflowInTimedeltaOperation,
4701 ZeroDivision,
4710}
4711
4712#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4715pub struct TemporalFailure {
4716 pub op: &'static str,
4718 pub pandas_error: PandasTemporalError,
4720 pub operands: Option<(i64, i64)>,
4725}
4726
4727impl TemporalFailure {
4728 #[must_use]
4729 pub const fn new(op: &'static str, pandas_error: PandasTemporalError) -> Self {
4730 Self {
4731 op,
4732 pandas_error,
4733 operands: None,
4734 }
4735 }
4736
4737 #[must_use]
4739 pub const fn with_operands(mut self, lhs: i64, rhs: i64) -> Self {
4740 self.operands = Some((lhs, rhs));
4741 self
4742 }
4743}
4744
4745#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4755pub struct TemporalRecovery {
4756 pub op: &'static str,
4758 pub pandas_error: PandasTemporalError,
4760 pub operands: Option<(i64, i64)>,
4762 pub recovered_as: i64,
4764}
4765
4766pub mod overflow_audit {
4775 use std::cell::RefCell;
4776
4777 use super::TemporalRecovery;
4778
4779 thread_local! {
4780 static LOG: RefCell<Option<Vec<TemporalRecovery>>> = const { RefCell::new(None) };
4781 }
4782
4783 pub fn enable() {
4785 LOG.with(|log| *log.borrow_mut() = Some(Vec::new()));
4786 }
4787
4788 pub fn disable() {
4790 LOG.with(|log| *log.borrow_mut() = None);
4791 }
4792
4793 #[must_use]
4795 pub fn is_enabled() -> bool {
4796 LOG.with(|log| log.borrow().is_some())
4797 }
4798
4799 #[must_use]
4801 pub fn drain() -> Vec<TemporalRecovery> {
4802 LOG.with(|log| match log.borrow_mut().as_mut() {
4803 Some(entries) => std::mem::take(entries),
4804 None => Vec::new(),
4805 })
4806 }
4807
4808 pub(super) fn record(entry: TemporalRecovery) {
4810 LOG.with(|log| {
4811 if let Some(entries) = log.borrow_mut().as_mut() {
4812 entries.push(entry);
4813 }
4814 });
4815 }
4816}
4817
4818#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
4831pub enum OverflowPolicy {
4832 #[default]
4835 SurfaceNat,
4836 Strict,
4838 HardenedNat,
4846}
4847
4848impl OverflowPolicy {
4849 pub fn resolve<T>(
4857 self,
4858 outcome: Result<T, TemporalFailure>,
4859 nat: T,
4860 ) -> Result<T, TemporalFailure> {
4861 self.resolve_recording(outcome, nat, i64::MIN)
4862 }
4863
4864 pub fn resolve_recording<T>(
4873 self,
4874 outcome: Result<T, TemporalFailure>,
4875 nat: T,
4876 recovered_as: i64,
4877 ) -> Result<T, TemporalFailure> {
4878 match (self, outcome) {
4879 (_, Ok(value)) => Ok(value),
4880 (Self::SurfaceNat, Err(_)) => Ok(nat),
4881 (Self::Strict, Err(failure)) => Err(failure),
4882 (Self::HardenedNat, Err(failure)) => {
4883 overflow_audit::record(TemporalRecovery {
4885 op: failure.op,
4886 pandas_error: failure.pandas_error,
4887 operands: failure.operands,
4888 recovered_as,
4889 });
4890 Ok(nat)
4891 }
4892 }
4893 }
4894}
4895
4896pub struct Timedelta;
4897
4898impl Timedelta {
4899 pub const NANOS_PER_MICRO: i64 = 1_000;
4900 pub const NANOS_PER_MILLI: i64 = 1_000_000;
4901 pub const NANOS_PER_SEC: i64 = 1_000_000_000;
4902 pub const NANOS_PER_MIN: i64 = 60 * Self::NANOS_PER_SEC;
4903 pub const NANOS_PER_HOUR: i64 = 60 * Self::NANOS_PER_MIN;
4904 pub const NANOS_PER_DAY: i64 = 24 * Self::NANOS_PER_HOUR;
4905 pub const NANOS_PER_WEEK: i64 = 7 * Self::NANOS_PER_DAY;
4906
4907 pub const NAT: i64 = i64::MIN;
4908
4909 pub fn parse(s: &str) -> Result<i64, TimedeltaError> {
4910 let s = s.trim();
4911
4912 if s.eq_ignore_ascii_case("nat") {
4913 return Ok(Self::NAT);
4914 }
4915
4916 let (negative, s) = if let Some(rest) = s.strip_prefix('-') {
4917 (true, rest.trim())
4918 } else {
4919 (false, s)
4920 };
4921
4922 if let Some(nanos) = Self::try_parse_time_format(s) {
4923 return Ok(if negative { -nanos } else { nanos });
4924 }
4925
4926 if let Some(nanos) = Self::try_parse_iso8601_duration(s) {
4927 return Ok(if negative { -nanos } else { nanos });
4928 }
4929
4930 let (units, clock) = Self::parse_compound(s)?;
4936 let units = if negative { -units } else { units };
4937 units.checked_add(clock).ok_or(TimedeltaError::Overflow)
4938 }
4939
4940 fn try_parse_iso8601_duration(s: &str) -> Option<i64> {
4948 let mut rest = s.strip_prefix('P')?;
4949 if rest.is_empty() {
4950 return None;
4951 }
4952 let mut total: i64 = 0;
4953 let mut saw_component = false;
4954 while !rest.is_empty() {
4955 if let Some(after_t) = rest.strip_prefix('T') {
4956 rest = after_t;
4957 continue;
4958 }
4959 let num_end = rest.find(|c: char| !c.is_ascii_digit() && c != '.')?;
4960 if num_end == 0 {
4961 return None;
4962 }
4963 let num_str = &rest[..num_end];
4964 let unit = rest.as_bytes()[num_end];
4965 let is_fractional = num_str.contains('.');
4966 rest = &rest[num_end + 1..];
4967
4968 let (multiplier, frac_ok) = match unit {
4969 b'W' => (Self::NANOS_PER_WEEK, false),
4970 b'D' => (Self::NANOS_PER_DAY, false),
4971 b'H' => (Self::NANOS_PER_HOUR, false),
4972 b'M' => (Self::NANOS_PER_MIN, false),
4973 b'S' => (Self::NANOS_PER_SEC, true),
4974 _ => return None,
4975 };
4976 if is_fractional {
4977 if !frac_ok {
4978 return None;
4979 }
4980 let value: f64 = num_str.parse().ok()?;
4981 let product = value * multiplier as f64;
4982 if !product.is_finite() || product.abs() >= 9223372036854775808.0 {
4983 return None;
4984 }
4985 total = total.checked_add(product.round() as i64)?;
4986 } else {
4987 let value: i64 = num_str.parse().ok()?;
4988 total = total.checked_add(value.checked_mul(multiplier)?)?;
4989 }
4990 saw_component = true;
4991 }
4992 saw_component.then_some(total)
4993 }
4994
4995 fn try_parse_time_format(s: &str) -> Option<i64> {
4996 let parts: Vec<&str> = s.split(':').collect();
4997 if parts.len() < 2 || parts.len() > 3 {
4998 return None;
4999 }
5000
5001 let hours: i64 = parts[0].parse().ok()?;
5002 let minutes: i64 = parts[1].parse().ok()?;
5003
5004 let (seconds, frac_nanos) = if parts.len() == 3 {
5005 if let Some((sec_str, frac_str)) = parts[2].split_once('.') {
5006 let sec: i64 = sec_str.parse().ok()?;
5007 if !frac_str.bytes().all(|byte| byte.is_ascii_digit()) {
5008 return None;
5009 }
5010 let mut frac = 0_i64;
5011 let taken = frac_str.len().min(9);
5012 for byte in frac_str.bytes().take(9) {
5013 frac = frac * 10 + i64::from(byte - b'0');
5014 }
5015 for _ in taken..9 {
5016 frac *= 10;
5017 }
5018 (sec, frac)
5019 } else {
5020 let sec: i64 = parts[2].parse().ok()?;
5021 (sec, 0)
5022 }
5023 } else {
5024 (0, 0)
5025 };
5026
5027 hours
5028 .checked_mul(Self::NANOS_PER_HOUR)?
5029 .checked_add(minutes.checked_mul(Self::NANOS_PER_MIN)?)?
5030 .checked_add(seconds.checked_mul(Self::NANOS_PER_SEC)?)?
5031 .checked_add(frac_nanos)
5032 }
5033
5034 fn parse_compound(s: &str) -> Result<(i64, i64), TimedeltaError> {
5040 let mut total: i64 = 0;
5041 let mut clock: i64 = 0;
5042 let mut remaining = s;
5043
5044 while !remaining.is_empty() {
5045 remaining = remaining.trim_start();
5046 if remaining.is_empty() {
5047 break;
5048 }
5049 if remaining.starts_with('-') {
5050 return Err(TimedeltaError::InvalidFormat(format!(
5051 "only leading negative signs are allowed: {s}"
5052 )));
5053 }
5054
5055 if remaining.contains(':')
5058 && let Some(time_nanos) = Self::try_parse_time_format(remaining)
5059 {
5060 clock = time_nanos;
5061 break;
5062 }
5063
5064 let num_end = remaining
5065 .find(|c: char| !c.is_ascii_digit() && c != '.' && c != '-')
5066 .unwrap_or(remaining.len());
5067
5068 if num_end == 0 {
5069 return Err(TimedeltaError::InvalidFormat(s.to_string()));
5070 }
5071
5072 let num_str = &remaining[..num_end];
5073 let num: f64 = num_str
5074 .parse()
5075 .map_err(|_| TimedeltaError::InvalidFormat(s.to_string()))?;
5076
5077 remaining = remaining[num_end..].trim_start();
5078
5079 let unit_end = remaining
5080 .find(|c: char| c.is_ascii_digit() || c.is_whitespace())
5081 .unwrap_or(remaining.len());
5082
5083 let unit = &remaining[..unit_end];
5084 remaining = &remaining[unit_end..];
5085
5086 let multiplier = Self::unit_to_nanos(unit)
5087 .ok_or_else(|| TimedeltaError::InvalidFormat(s.to_string()))?;
5088
5089 let product = num * multiplier as f64;
5094 if !product.is_finite() || product.abs() >= 9223372036854775808.0 {
5095 return Err(TimedeltaError::Overflow);
5096 }
5097 let nanos = product.round() as i64;
5098 total = total.checked_add(nanos).ok_or(TimedeltaError::Overflow)?;
5099 }
5100
5101 Ok((total, clock))
5111 }
5112
5113 #[must_use]
5127 pub fn unit_to_nanos(unit: &str) -> Option<i64> {
5128 match unit.to_lowercase().as_str() {
5129 "w" | "week" | "weeks" => Some(Self::NANOS_PER_WEEK),
5130 "d" | "day" | "days" => Some(Self::NANOS_PER_DAY),
5131 "h" | "hr" | "hour" | "hours" => Some(Self::NANOS_PER_HOUR),
5132 "m" | "min" | "minute" | "minutes" | "t" => Some(Self::NANOS_PER_MIN),
5133 "s" | "sec" | "second" | "seconds" => Some(Self::NANOS_PER_SEC),
5134 "ms" | "milli" | "millis" | "millisecond" | "milliseconds" | "l" => {
5135 Some(Self::NANOS_PER_MILLI)
5136 }
5137 "us" | "µs" | "micro" | "micros" | "microsecond" | "microseconds" | "u" => {
5138 Some(Self::NANOS_PER_MICRO)
5139 }
5140 "ns" | "nano" | "nanos" | "nanosecond" | "nanoseconds" | "n" => Some(1),
5141 "" => Some(Self::NANOS_PER_DAY),
5142 _ => None,
5143 }
5144 }
5145
5146 pub fn components(nanos: i64) -> TimedeltaComponents {
5147 if nanos == Self::NAT {
5148 return TimedeltaComponents::default();
5149 }
5150
5151 let days = nanos.div_euclid(Self::NANOS_PER_DAY);
5156 let rem = nanos.rem_euclid(Self::NANOS_PER_DAY);
5157
5158 let hours = rem / Self::NANOS_PER_HOUR;
5159 let rem = rem % Self::NANOS_PER_HOUR;
5160
5161 let minutes = rem / Self::NANOS_PER_MIN;
5162 let rem = rem % Self::NANOS_PER_MIN;
5163
5164 let seconds = rem / Self::NANOS_PER_SEC;
5165 let rem = rem % Self::NANOS_PER_SEC;
5166
5167 let milliseconds = rem / Self::NANOS_PER_MILLI;
5168 let rem = rem % Self::NANOS_PER_MILLI;
5169
5170 let microseconds = rem / Self::NANOS_PER_MICRO;
5171 let nanoseconds = rem % Self::NANOS_PER_MICRO;
5172
5173 TimedeltaComponents {
5174 days,
5175 hours,
5176 minutes,
5177 seconds,
5178 milliseconds,
5179 microseconds,
5180 nanoseconds,
5181 }
5182 }
5183
5184 pub fn total_seconds(nanos: i64) -> f64 {
5185 if nanos == Self::NAT {
5186 f64::NAN
5187 } else {
5188 nanos as f64 / Self::NANOS_PER_SEC as f64
5189 }
5190 }
5191
5192 #[must_use]
5196 pub fn as_unit(nanos: i64, unit: &str) -> f64 {
5197 if nanos == Self::NAT {
5198 return f64::NAN;
5199 }
5200 let nanos_f = nanos as f64;
5201 match unit {
5202 "ns" | "nanoseconds" => nanos_f,
5203 "us" | "microseconds" => nanos_f / Self::NANOS_PER_MICRO as f64,
5204 "ms" | "milliseconds" => nanos_f / Self::NANOS_PER_MILLI as f64,
5205 "s" | "seconds" => nanos_f / Self::NANOS_PER_SEC as f64,
5206 "m" | "minutes" => nanos_f / Self::NANOS_PER_MIN as f64,
5207 "h" | "hours" => nanos_f / Self::NANOS_PER_HOUR as f64,
5208 "D" | "days" => nanos_f / Self::NANOS_PER_DAY as f64,
5209 _ => f64::NAN,
5210 }
5211 }
5212
5213 #[must_use]
5233 pub fn days(nanos: i64) -> Option<i64> {
5234 if nanos == Self::NAT {
5235 return None;
5236 }
5237 Some(nanos.div_euclid(Self::NANOS_PER_DAY))
5239 }
5240
5241 #[must_use]
5244 pub fn seconds(nanos: i64) -> Option<i64> {
5245 if nanos == Self::NAT {
5246 return None;
5247 }
5248 Some(nanos.rem_euclid(Self::NANOS_PER_DAY) / Self::NANOS_PER_SEC)
5250 }
5251
5252 #[must_use]
5255 pub fn microseconds(nanos: i64) -> Option<i64> {
5256 if nanos == Self::NAT {
5257 return None;
5258 }
5259 Some(nanos.rem_euclid(Self::NANOS_PER_SEC) / Self::NANOS_PER_MICRO)
5260 }
5261
5262 #[must_use]
5265 pub fn nanoseconds(nanos: i64) -> Option<i64> {
5266 if nanos == Self::NAT {
5267 return None;
5268 }
5269 Some(nanos.rem_euclid(Self::NANOS_PER_MICRO))
5270 }
5271
5272 #[must_use]
5278 pub const fn string_resolution(nanos: i64) -> TimedeltaStringResolution {
5279 if nanos == Self::NAT || nanos.rem_euclid(Self::NANOS_PER_DAY) == 0 {
5280 TimedeltaStringResolution::Days
5281 } else {
5282 TimedeltaStringResolution::Full
5283 }
5284 }
5285
5286 #[must_use]
5294 pub fn format_at_resolution(nanos: i64, resolution: TimedeltaStringResolution) -> String {
5295 if nanos == Self::NAT {
5296 return "NaT".to_string();
5297 }
5298 match resolution {
5299 TimedeltaStringResolution::Full => Self::format(nanos),
5300 TimedeltaStringResolution::Days => {
5303 format!("{} days", nanos.div_euclid(Self::NANOS_PER_DAY))
5304 }
5305 }
5306 }
5307
5308 pub fn format(nanos: i64) -> String {
5309 use std::fmt::Write as _;
5310
5311 if nanos == Self::NAT {
5312 return "NaT".to_string();
5313 }
5314
5315 let days = nanos.div_euclid(Self::NANOS_PER_DAY);
5321 let rem = nanos.rem_euclid(Self::NANOS_PER_DAY);
5322 let hours = rem / Self::NANOS_PER_HOUR;
5323 let minutes = (rem % Self::NANOS_PER_HOUR) / Self::NANOS_PER_MIN;
5324 let seconds = (rem % Self::NANOS_PER_MIN) / Self::NANOS_PER_SEC;
5325 let frac = rem % Self::NANOS_PER_SEC;
5326
5327 let mut result = String::with_capacity(32);
5330 let _ = write!(result, "{days} days ");
5331 if days < 0 {
5333 result.push('+');
5334 }
5335 let _ = write!(result, "{hours:02}:{minutes:02}:{seconds:02}");
5336 if frac > 0 {
5337 if frac % 1_000 == 0 {
5341 let _ = write!(result, ".{:06}", frac / 1_000);
5342 } else {
5343 let _ = write!(result, ".{frac:09}");
5344 }
5345 }
5346 result
5347 }
5348
5349 pub fn from_unit(value: f64, unit: &str) -> Result<i64, TimedeltaError> {
5366 let multiplier = Self::unit_to_nanos(unit)
5367 .ok_or_else(|| TimedeltaError::InvalidFormat(unit.to_string()))?;
5368 if value.is_nan() {
5369 return Ok(Self::NAT);
5370 }
5371 let product = value * multiplier as f64;
5372 if !product.is_finite() || product.abs() >= 9223372036854775808.0 {
5373 return Err(TimedeltaError::Overflow);
5374 }
5375 Ok(product.round() as i64)
5376 }
5377
5378 pub fn try_add(a: i64, b: i64) -> Result<i64, TemporalFailure> {
5418 if a == Self::NAT || b == Self::NAT {
5419 return Ok(Self::NAT);
5420 }
5421 a.checked_add(b).ok_or(
5422 TemporalFailure::new("Timedelta::add", PandasTemporalError::Overflow)
5423 .with_operands(a, b),
5424 )
5425 }
5426
5427 #[must_use]
5429 pub fn add(a: i64, b: i64) -> i64 {
5430 Self::try_add(a, b).unwrap_or(Self::NAT)
5431 }
5432
5433 pub fn try_sub(a: i64, b: i64) -> Result<i64, TemporalFailure> {
5438 if a == Self::NAT || b == Self::NAT {
5439 return Ok(Self::NAT);
5440 }
5441 a.checked_sub(b).ok_or(
5442 TemporalFailure::new("Timedelta::sub", PandasTemporalError::Overflow)
5443 .with_operands(a, b),
5444 )
5445 }
5446
5447 #[must_use]
5449 pub fn sub(a: i64, b: i64) -> i64 {
5450 Self::try_sub(a, b).unwrap_or(Self::NAT)
5451 }
5452
5453 #[must_use]
5471 pub fn neg(a: i64) -> i64 {
5472 if a == Self::NAT {
5473 return Self::NAT;
5474 }
5475 a.saturating_neg()
5476 }
5477
5478 #[must_use]
5485 pub fn abs(a: i64) -> i64 {
5486 if a == Self::NAT {
5487 return Self::NAT;
5488 }
5489 a.saturating_abs()
5490 }
5491
5492 #[must_use]
5498 pub fn mul_scalar(a: i64, factor: i64) -> i64 {
5499 Self::try_mul_scalar(a, factor).unwrap_or(Self::NAT)
5500 }
5501
5502 #[must_use]
5523 pub fn mul_scalar_with_policy(a: i64, factor: i64, policy: OverflowPolicy) -> i64 {
5524 if a == Self::NAT {
5525 return Self::NAT;
5526 }
5527 if matches!(policy, OverflowPolicy::Strict) {
5528 return a.wrapping_mul(factor);
5529 }
5530 policy
5531 .resolve_recording(Self::try_mul_scalar(a, factor), Self::NAT, Self::NAT)
5532 .unwrap_or(Self::NAT)
5533 }
5534
5535 pub fn try_mul_scalar(a: i64, factor: i64) -> Result<i64, TemporalFailure> {
5543 if a == Self::NAT {
5544 return Ok(Self::NAT);
5545 }
5546 a.checked_mul(factor).ok_or(
5547 TemporalFailure::new("Timedelta::mul_scalar", PandasTemporalError::Overflow)
5548 .with_operands(a, factor),
5549 )
5550 }
5551
5552 #[must_use]
5562 pub fn div_scalar(a: i64, divisor: i64) -> i64 {
5563 Self::try_div_scalar(a, divisor).unwrap_or(Self::NAT)
5564 }
5565
5566 pub fn try_div_scalar(a: i64, divisor: i64) -> Result<i64, TemporalFailure> {
5581 if divisor == 0 {
5582 return Err(TemporalFailure::new(
5583 "Timedelta::div_scalar",
5584 PandasTemporalError::ZeroDivision,
5585 )
5586 .with_operands(a, divisor));
5587 }
5588 if a == Self::NAT {
5589 return Ok(Self::NAT);
5590 }
5591 Ok(Self::div_scalar_inner(a, divisor))
5592 }
5593
5594 fn div_scalar_inner(a: i64, divisor: i64) -> i64 {
5595 let q = a / divisor;
5600 let r = a % divisor;
5601 if r != 0 && (r < 0) != (divisor < 0) {
5605 q - 1
5606 } else {
5607 q
5608 }
5609 }
5610
5611 #[must_use]
5615 pub fn div_timedelta(a: i64, b: i64) -> f64 {
5616 if a == Self::NAT || b == Self::NAT {
5617 return f64::NAN;
5618 }
5619 (a as f64) / (b as f64)
5620 }
5621
5622 #[must_use]
5630 pub fn isoformat(nanos: i64) -> String {
5631 use std::fmt::Write as _;
5632
5633 if nanos == Self::NAT {
5634 return "NaT".to_string();
5635 }
5636
5637 let days = nanos.div_euclid(Self::NANOS_PER_DAY);
5638 let remaining = nanos.rem_euclid(Self::NANOS_PER_DAY);
5639
5640 let hours = remaining / Self::NANOS_PER_HOUR;
5641 let remaining = remaining % Self::NANOS_PER_HOUR;
5642
5643 let minutes = remaining / Self::NANOS_PER_MIN;
5644 let remaining = remaining % Self::NANOS_PER_MIN;
5645
5646 let seconds = remaining / Self::NANOS_PER_SEC;
5647 let sub_sec_nanos = remaining % Self::NANOS_PER_SEC;
5648
5649 let mut result = String::with_capacity(40);
5653 let _ = write!(result, "P{days}DT{hours}H{minutes}M{seconds}");
5655 if sub_sec_nanos != 0 {
5656 result.push('.');
5657 let _ = write!(result, "{sub_sec_nanos:09}");
5658 while result.ends_with('0') {
5659 result.pop();
5660 }
5661 }
5662 result.push('S');
5663 result
5664 }
5665
5666 #[must_use]
5670 pub fn floor(nanos: i64, freq: &str) -> i64 {
5671 if nanos == Self::NAT {
5672 return Self::NAT;
5673 }
5674 let Some(unit_nanos) = Self::unit_to_nanos(freq) else {
5675 return Self::NAT;
5676 };
5677 if unit_nanos == 0 {
5678 return Self::NAT;
5679 }
5680 nanos
5681 .div_euclid(unit_nanos)
5682 .checked_mul(unit_nanos)
5683 .unwrap_or(Self::NAT)
5684 }
5685
5686 #[must_use]
5693 pub fn ceil(nanos: i64, freq: &str) -> i64 {
5694 if nanos == Self::NAT {
5695 return Self::NAT;
5696 }
5697 let Some(unit_nanos) = Self::unit_to_nanos(freq) else {
5698 return Self::NAT;
5699 };
5700 if unit_nanos == 0 {
5701 return Self::NAT;
5702 }
5703 let remainder = nanos.rem_euclid(unit_nanos);
5704 if remainder == 0 {
5705 nanos
5706 } else {
5707 nanos
5708 .checked_add(unit_nanos - remainder)
5709 .unwrap_or(Self::NAT)
5710 }
5711 }
5712
5713 #[must_use]
5718 pub fn round(nanos: i64, freq: &str) -> i64 {
5719 if nanos == Self::NAT {
5720 return Self::NAT;
5721 }
5722 let Some(unit_nanos) = Self::unit_to_nanos(freq) else {
5723 return Self::NAT;
5724 };
5725 if unit_nanos == 0 {
5726 return Self::NAT;
5727 }
5728 let negative = nanos < 0;
5729 let abs_nanos = nanos.saturating_abs();
5730
5731 let quotient = abs_nanos / unit_nanos;
5732 let remainder = abs_nanos % unit_nanos;
5733 let half = unit_nanos / 2;
5734
5735 let round_up = || {
5743 quotient
5744 .checked_add(1)
5745 .and_then(|q| q.checked_mul(unit_nanos))
5746 };
5747 let rounded = if remainder > half {
5748 round_up()
5749 } else if remainder < half {
5750 Some(quotient * unit_nanos)
5751 } else {
5752 if quotient % 2 == 0 {
5754 Some(quotient * unit_nanos)
5755 } else {
5756 round_up()
5757 }
5758 };
5759
5760 match rounded {
5761 Some(rounded) => {
5764 if negative {
5765 -rounded
5766 } else {
5767 rounded
5768 }
5769 }
5770 None => Self::NAT,
5771 }
5772 }
5773}
5774
5775#[derive(Debug, Clone, PartialEq, Eq, Error)]
5783pub enum TimeZoneError {
5784 #[error("'{0}'")]
5787 Unknown(String),
5788 #[error("{0}")]
5791 NonExistent(String),
5792 #[error("Cannot infer dst time from {0}, try using the 'ambiguous' argument")]
5794 Ambiguous(String),
5795}
5796
5797enum Zone {
5799 Fixed(chrono::FixedOffset),
5800 Named(chrono_tz::Tz),
5801}
5802
5803impl Zone {
5804 fn parse(tz: &str) -> Result<Self, TimeZoneError> {
5808 use chrono::Offset;
5809 let name = tz.trim();
5810 if name == "UTC" || name == "Z" {
5811 return Ok(Self::Fixed(chrono::Utc.fix()));
5812 }
5813 let offset = name
5814 .strip_prefix("UTC")
5815 .filter(|rest| rest.starts_with(['+', '-']))
5816 .unwrap_or(name);
5817 let bytes = offset.as_bytes();
5818 if bytes.len() == 6
5819 && matches!(bytes[0], b'+' | b'-')
5820 && bytes[3] == b':'
5821 && [1, 2, 4, 5].iter().all(|&i| bytes[i].is_ascii_digit())
5822 {
5823 let hours: i32 = offset[1..3].parse().unwrap_or(24);
5824 let minutes: i32 = offset[4..6].parse().unwrap_or(60);
5825 let sign = if bytes[0] == b'-' { -1 } else { 1 };
5826 return (hours <= 23 && minutes <= 59)
5827 .then(|| chrono::FixedOffset::east_opt(sign * (hours * 3_600 + minutes * 60)))
5828 .flatten()
5829 .map(Self::Fixed)
5830 .ok_or_else(|| TimeZoneError::Unknown(name.to_owned()));
5831 }
5832 name.parse::<chrono_tz::Tz>()
5833 .map(Self::Named)
5834 .map_err(|_| TimeZoneError::Unknown(name.to_owned()))
5835 }
5836
5837 fn offset_seconds(&self, utc_nanos: i64) -> i32 {
5839 use chrono::{Offset, TimeZone};
5840 match self {
5841 Self::Fixed(offset) => offset.local_minus_utc(),
5842 Self::Named(zone) => {
5843 let utc = chrono::DateTime::from_timestamp_nanos(utc_nanos).naive_utc();
5844 zone.offset_from_utc_datetime(&utc).fix().local_minus_utc()
5845 }
5846 }
5847 }
5848}
5849
5850pub fn tz_validate(tz: &str) -> Result<(), TimeZoneError> {
5852 Zone::parse(tz).map(|_| ())
5853}
5854
5855pub fn tz_canonical_name(tz: &str) -> Result<String, TimeZoneError> {
5859 Ok(match Zone::parse(tz)? {
5860 Zone::Fixed(offset) if offset.local_minus_utc() == 0 => "UTC".to_owned(),
5861 Zone::Fixed(offset) => format!("UTC{offset}"),
5862 Zone::Named(_) => tz.trim().to_owned(),
5863 })
5864}
5865
5866pub fn tz_abbreviation(tz: &str, utc_nanos: i64) -> Result<String, TimeZoneError> {
5870 use chrono::TimeZone;
5871 match Zone::parse(tz)? {
5872 Zone::Named(zone) => {
5873 let utc = chrono::DateTime::from_timestamp_nanos(utc_nanos).naive_utc();
5874 let offset = zone.offset_from_utc_datetime(&utc);
5875 Ok(chrono_tz::OffsetName::abbreviation(&offset)
5876 .map_or_else(|| tz.trim().to_owned(), str::to_owned))
5877 }
5878 Zone::Fixed(_) => tz_canonical_name(tz),
5879 }
5880}
5881
5882pub fn tz_offset_seconds(tz: &str, utc_nanos: i64) -> Result<i32, TimeZoneError> {
5886 Ok(Zone::parse(tz)?.offset_seconds(utc_nanos))
5887}
5888
5889pub fn tz_utc_to_wall_nanos(tz: &str, utc_nanos: i64) -> Result<i64, TimeZoneError> {
5892 if utc_nanos == i64::MIN {
5893 return Ok(utc_nanos);
5894 }
5895 let offset = Zone::parse(tz)?.offset_seconds(utc_nanos);
5896 Ok(utc_nanos.saturating_add(i64::from(offset) * 1_000_000_000))
5897}
5898
5899pub fn tz_wall_to_utc_nanos(tz: &str, wall_nanos: i64) -> Result<i64, TimeZoneError> {
5904 tz_wall_to_utc_nanos_with(tz, wall_nanos, AmbiguousTime::Raise, NonexistentTime::Raise)
5905}
5906
5907#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5911pub enum AmbiguousTime {
5912 Raise,
5913 Earliest,
5914 Latest,
5915 NaT,
5916}
5917
5918#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5924pub enum NonexistentTime {
5925 Raise,
5926 ShiftForward,
5927 ShiftBackward,
5928 NaT,
5929 Shift(i64),
5930}
5931
5932pub fn tz_wall_to_utc_nanos_with(
5935 tz: &str,
5936 wall_nanos: i64,
5937 ambiguous: AmbiguousTime,
5938 nonexistent: NonexistentTime,
5939) -> Result<i64, TimeZoneError> {
5940 if wall_nanos == i64::MIN {
5941 return Ok(wall_nanos);
5942 }
5943 wall_to_utc_in(&Zone::parse(tz)?, wall_nanos, ambiguous, nonexistent)
5944}
5945
5946const NANOS_PER_HOUR: i64 = 3_600_000_000_000;
5947const NANOS_PER_SECOND: i64 = 1_000_000_000;
5948
5949pub fn tz_utc_to_wall_nanos_all(tz: &str, utc: &[i64]) -> Result<Vec<i64>, TimeZoneError> {
5959 let zone = Zone::parse(tz)?;
5960 let mut offsets = HourOffsets::new(&zone);
5961 Ok(utc
5962 .iter()
5963 .map(|&nanos| {
5964 if nanos == i64::MIN {
5965 nanos
5966 } else {
5967 nanos.saturating_add(i64::from(offsets.at(nanos)) * NANOS_PER_SECOND)
5968 }
5969 })
5970 .collect())
5971}
5972
5973pub fn tz_wall_to_utc_nanos_all(
5982 tz: &str,
5983 walls: &[i64],
5984 ambiguous: AmbiguousTime,
5985 nonexistent: NonexistentTime,
5986) -> Result<Vec<i64>, TimeZoneError> {
5987 let zone = Zone::parse(tz)?;
5988 let mut hour = i64::MIN;
5989 let mut checked = false;
5990 let mut simple: Option<i32> = None;
5991 walls
5992 .iter()
5993 .map(|&wall| {
5994 if wall == i64::MIN {
5995 return Ok(wall);
5996 }
5997 let at = wall.div_euclid(NANOS_PER_HOUR);
5998 if at == hour {
5999 if !checked {
6000 checked = true;
6001 simple = simple_local_hour(&zone, at);
6002 }
6003 if let Some(offset) = simple
6004 && let Some(utc) = wall.checked_sub(i64::from(offset) * NANOS_PER_SECOND)
6005 {
6006 return Ok(utc);
6007 }
6008 } else {
6009 hour = at;
6010 checked = false;
6011 simple = None;
6012 }
6013 wall_to_utc_in(&zone, wall, ambiguous, nonexistent)
6014 })
6015 .collect()
6016}
6017
6018struct HourOffsets<'a> {
6025 zone: &'a Zone,
6026 hour: i64,
6027 offset: i32,
6028 uniform: Option<bool>,
6030}
6031
6032impl<'a> HourOffsets<'a> {
6033 fn new(zone: &'a Zone) -> Self {
6034 Self {
6035 zone,
6036 hour: i64::MIN,
6037 offset: 0,
6038 uniform: None,
6039 }
6040 }
6041
6042 fn at(&mut self, utc: i64) -> i32 {
6043 if let Zone::Fixed(fixed) = self.zone {
6044 return fixed.local_minus_utc();
6045 }
6046 let hour = utc.div_euclid(NANOS_PER_HOUR);
6047 if hour != self.hour {
6048 self.hour = hour;
6049 self.uniform = None;
6050 self.offset = self.zone.offset_seconds(utc);
6051 return self.offset;
6052 }
6053 let uniform = *self.uniform.get_or_insert_with(|| {
6054 hour.checked_mul(NANOS_PER_HOUR).is_some_and(|start| {
6055 self.zone.offset_seconds(start) == self.offset
6056 && start
6057 .checked_add(NANOS_PER_HOUR - 1)
6058 .is_some_and(|end| self.zone.offset_seconds(end) == self.offset)
6059 })
6060 });
6061 if uniform {
6062 self.offset
6063 } else {
6064 self.zone.offset_seconds(utc)
6065 }
6066 }
6067}
6068
6069fn simple_local_hour(zone: &Zone, hour: i64) -> Option<i32> {
6074 let start = hour.checked_mul(NANOS_PER_HOUR)?;
6075 let end = start.checked_add(NANOS_PER_HOUR - 1)?;
6076 let first = single_local_offset(zone, start)?;
6077 (single_local_offset(zone, end)? == first).then_some(first)
6078}
6079
6080fn single_local_offset(zone: &Zone, wall_nanos: i64) -> Option<i32> {
6083 use chrono::{LocalResult, Offset, TimeZone};
6084 let naive = chrono::DateTime::from_timestamp_nanos(wall_nanos).naive_utc();
6085 match zone {
6086 Zone::Fixed(offset) => Some(offset.local_minus_utc()),
6087 Zone::Named(zone) => match zone.from_local_datetime(&naive) {
6088 LocalResult::Single(at) => Some(at.offset().fix().local_minus_utc()),
6089 _ => None,
6090 },
6091 }
6092}
6093
6094fn wall_text(wall_nanos: i64) -> String {
6098 let naive = chrono::DateTime::from_timestamp_nanos(wall_nanos).naive_utc();
6099 let seconds = naive.format("%Y-%m-%d %H:%M:%S");
6100 let nanos = wall_nanos.rem_euclid(NANOS_PER_SECOND);
6101 if nanos == 0 {
6102 format!("{seconds}")
6103 } else if nanos % 1_000 == 0 {
6104 format!("{seconds}.{:06}", nanos / 1_000)
6105 } else {
6106 format!("{seconds}.{nanos:09}")
6107 }
6108}
6109
6110fn pandas_shift_offset(zone: &Zone, moved: i64, forward: bool) -> i32 {
6116 const DAY: i64 = 86_400 * NANOS_PER_SECOND;
6117 let here = zone.offset_seconds(moved);
6118 let first = zone.offset_seconds(i64::MIN + 1);
6119 let in_force = if forward {
6120 here >= 0 || first > 0
6121 } else {
6122 first < 0
6123 };
6124 if in_force {
6125 return here;
6126 }
6127 (1..=1_100_i64)
6130 .filter_map(|day| moved.checked_add(day * DAY))
6131 .map(|at| zone.offset_seconds(at))
6132 .find(|&offset| offset != here)
6133 .unwrap_or(here)
6134}
6135
6136fn wall_to_utc_in(
6138 zone: &Zone,
6139 wall_nanos: i64,
6140 ambiguous: AmbiguousTime,
6141 nonexistent: NonexistentTime,
6142) -> Result<i64, TimeZoneError> {
6143 use chrono::{LocalResult, TimeZone};
6144 let naive = chrono::DateTime::from_timestamp_nanos(wall_nanos).naive_utc();
6145 let local = match zone {
6146 Zone::Fixed(offset) => offset
6147 .from_local_datetime(&naive)
6148 .map(|at| at.fixed_offset()),
6149 Zone::Named(zone) => zone.from_local_datetime(&naive).map(|at| at.fixed_offset()),
6150 };
6151 let nanos_of = |at: chrono::DateTime<chrono::FixedOffset>| {
6152 at.timestamp_nanos_opt()
6153 .ok_or_else(|| TimeZoneError::NonExistent(wall_text(wall_nanos)))
6154 };
6155 match local {
6156 LocalResult::Single(at) => nanos_of(at),
6157 LocalResult::Ambiguous(earliest, latest) => match ambiguous {
6158 AmbiguousTime::Raise => Err(TimeZoneError::Ambiguous(wall_text(wall_nanos))),
6159 AmbiguousTime::Earliest => nanos_of(earliest),
6160 AmbiguousTime::Latest => nanos_of(latest),
6161 AmbiguousTime::NaT => Ok(i64::MIN),
6162 },
6163 LocalResult::None => match nonexistent {
6164 NonexistentTime::Raise => Err(TimeZoneError::NonExistent(wall_text(wall_nanos))),
6165 NonexistentTime::NaT => Ok(i64::MIN),
6166 NonexistentTime::Shift(delta) => {
6167 let shifted = wall_nanos
6168 .checked_add(delta)
6169 .ok_or_else(|| TimeZoneError::NonExistent(wall_text(wall_nanos)))?;
6170 if shifted == i64::MIN {
6171 return Ok(shifted);
6172 }
6173 wall_to_utc_in(zone, shifted, ambiguous, NonexistentTime::Raise)
6174 }
6175 NonexistentTime::ShiftForward | NonexistentTime::ShiftBackward => {
6176 let forward = nonexistent == NonexistentTime::ShiftForward;
6185 let into_hour = wall_nanos.rem_euclid(NANOS_PER_HOUR);
6186 let moved = if forward {
6187 wall_nanos.checked_add(NANOS_PER_HOUR - into_hour)
6188 } else {
6189 wall_nanos.checked_sub(into_hour + 1)
6190 };
6191 moved
6192 .and_then(|moved| {
6193 let offset = pandas_shift_offset(zone, moved, forward);
6194 moved.checked_sub(i64::from(offset) * NANOS_PER_SECOND)
6195 })
6196 .ok_or_else(|| TimeZoneError::NonExistent(wall_text(wall_nanos)))
6197 }
6198 },
6199 }
6200}
6201
6202#[must_use]
6212pub fn strftime_python(wall_nanos: i64, format: &str, zone: Option<(i32, &str)>) -> String {
6213 const DAYS: [&str; 7] = [
6214 "Sunday",
6215 "Monday",
6216 "Tuesday",
6217 "Wednesday",
6218 "Thursday",
6219 "Friday",
6220 "Saturday",
6221 ];
6222 const MONTHS: [&str; 12] = [
6223 "January",
6224 "February",
6225 "March",
6226 "April",
6227 "May",
6228 "June",
6229 "July",
6230 "August",
6231 "September",
6232 "October",
6233 "November",
6234 "December",
6235 ];
6236 let total_secs = wall_nanos.div_euclid(1_000_000_000);
6239 let sub_nanos = wall_nanos.rem_euclid(1_000_000_000);
6240 let days = total_secs.div_euclid(86_400);
6241 let secs_of_day = total_secs.rem_euclid(86_400);
6242 let (year, month, day) = civil_from_days(days);
6243 let (hour, minute, second) = (
6244 secs_of_day / 3_600,
6245 (secs_of_day % 3_600) / 60,
6246 secs_of_day % 60,
6247 );
6248 let hour12 = if hour % 12 == 0 { 12 } else { hour % 12 };
6249 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 };
6252 let (iso_year, iso_week) = {
6253 let week = (yday + 1 - iso_weekday + 10).div_euclid(7);
6254 if week < 1 {
6255 (year - 1, iso_weeks_in_year(year - 1))
6256 } else if week > iso_weeks_in_year(year) {
6257 (year + 1, 1)
6258 } else {
6259 (year, week)
6260 }
6261 };
6262 let month_name = MONTHS[(month as usize).saturating_sub(1) % 12];
6263 let day_name = DAYS[weekday as usize];
6264
6265 let mut out = String::with_capacity(format.len().saturating_add(16));
6266 let mut chars = format.chars().peekable();
6267 while let Some(ch) = chars.next() {
6268 if ch != '%' {
6269 out.push(ch);
6270 continue;
6271 }
6272 let flag = chars.next_if(|c| matches!(c, '-' | '_' | '0' | '^'));
6273 let Some(conversion) = chars.next() else {
6274 out.push('%');
6275 if let Some(flag) = flag {
6276 out.push(flag);
6277 }
6278 break;
6279 };
6280 let number = |value: i64, width: usize, pad: char| -> String {
6283 match flag.unwrap_or(pad) {
6284 '-' => value.to_string(),
6285 '_' | ' ' => format!("{value:>width$}"),
6286 _ => format!("{value:0width$}"),
6287 }
6288 };
6289 let text = |value: &str| -> String {
6290 if flag == Some('^') {
6291 value.to_uppercase()
6292 } else {
6293 value.to_owned()
6294 }
6295 };
6296 let piece = match conversion {
6297 'a' => text(&day_name[..3]),
6298 'A' => text(day_name),
6299 'b' | 'h' => text(&month_name[..3]),
6300 'B' => text(month_name),
6301 'c' => text(&strftime_python(wall_nanos, "%a %b %e %H:%M:%S %Y", zone)),
6302 'C' => number(year.div_euclid(100), 2, '0'),
6303 'd' => number(i64::from(day), 2, '0'),
6304 'D' | 'x' => strftime_python(wall_nanos, "%m/%d/%y", zone),
6305 'e' => number(i64::from(day), 2, ' '),
6306 'f' => number(sub_nanos / 1_000, 6, '0'),
6307 'F' => strftime_python(wall_nanos, "%Y-%m-%d", zone),
6308 'g' => number(iso_year.rem_euclid(100), 2, '0'),
6309 'G' => number(iso_year, 1, '0'),
6310 'H' => number(hour, 2, '0'),
6311 'I' => number(hour12, 2, '0'),
6312 'j' => number(yday + 1, 3, '0'),
6313 'k' => number(hour, 2, ' '),
6314 'l' => number(hour12, 2, ' '),
6315 'm' => number(i64::from(month), 2, '0'),
6316 'M' => number(minute, 2, '0'),
6317 'n' => "\n".to_owned(),
6318 'p' => text(if hour < 12 { "AM" } else { "PM" }),
6319 'P' => (if hour < 12 { "am" } else { "pm" }).to_owned(),
6320 'r' => strftime_python(wall_nanos, "%I:%M:%S %p", zone),
6321 'R' => strftime_python(wall_nanos, "%H:%M", zone),
6322 'S' => number(second, 2, '0'),
6323 't' => "\t".to_owned(),
6324 'T' | 'X' => strftime_python(wall_nanos, "%H:%M:%S", zone),
6325 'u' => number(iso_weekday, 1, '0'),
6326 'U' => number((yday + 7 - weekday).div_euclid(7), 2, '0'),
6327 'V' => number(iso_week, 2, '0'),
6328 'w' => number(weekday, 1, '0'),
6329 'W' => number(
6330 (yday + 7 - (weekday + 6).rem_euclid(7)).div_euclid(7),
6331 2,
6332 '0',
6333 ),
6334 'y' => number(year.rem_euclid(100), 2, '0'),
6335 'Y' => number(year, 1, '0'),
6336 'z' => zone.map_or_else(String::new, |(offset, _)| {
6337 let sign = if offset < 0 { '-' } else { '+' };
6338 let offset = offset.unsigned_abs();
6339 let (h, m, s) = (offset / 3_600, (offset % 3_600) / 60, offset % 60);
6340 if s == 0 {
6341 format!("{sign}{h:02}{m:02}")
6342 } else {
6343 format!("{sign}{h:02}{m:02}{s:02}")
6344 }
6345 }),
6346 'Z' => zone.map_or_else(String::new, |(_, name)| text(name)),
6347 '%' => "%".to_owned(),
6348 other => {
6349 out.push('%');
6351 if let Some(flag) = flag {
6352 out.push(flag);
6353 }
6354 out.push(other);
6355 continue;
6356 }
6357 };
6358 out.push_str(&piece);
6359 }
6360 out
6361}
6362
6363#[must_use]
6367pub fn strftime_in_zone(nanos: i64, format: &str, tz: Option<&str>) -> String {
6368 let aware = tz.and_then(|zone| {
6369 let offset = tz_offset_seconds(zone, nanos).ok()?;
6370 let name = tz_abbreviation(zone, nanos).ok()?;
6371 Some((offset, name))
6372 });
6373 match aware {
6374 Some((offset, name)) => strftime_python(
6375 nanos.saturating_add(i64::from(offset) * 1_000_000_000),
6376 format,
6377 Some((offset, &name)),
6378 ),
6379 None => strftime_python(nanos, format, None),
6380 }
6381}
6382
6383#[must_use]
6389pub fn timestamp_text(nanos: i64) -> String {
6390 let mut text = strftime_python(nanos, "%Y-%m-%d %H:%M:%S", None);
6391 let fraction = nanos.rem_euclid(1_000_000_000);
6392 if fraction % 1_000 != 0 {
6393 text.push_str(&format!(".{fraction:09}"));
6394 } else if fraction != 0 {
6395 text.push_str(&format!(".{:06}", fraction / 1_000));
6396 }
6397 text
6398}
6399
6400#[must_use]
6404pub fn timestamp_text_in_zone(nanos: i64, tz: &str) -> String {
6405 let offset = tz_offset_seconds(tz, nanos).unwrap_or(0);
6406 let mut text = timestamp_text(nanos.saturating_add(i64::from(offset) * 1_000_000_000));
6407 let sign = if offset < 0 { '-' } else { '+' };
6408 let minutes = offset.unsigned_abs() / 60;
6409 text.push_str(&format!("{sign}{:02}:{:02}", minutes / 60, minutes % 60));
6410 text
6411}
6412
6413#[must_use]
6421pub fn add_calendar_months_nanos(nanos: i64, months: i64) -> Option<i64> {
6422 const DAY: i64 = 86_400_000_000_000;
6423 let moved = add_calendar_months_days(nanos.div_euclid(DAY), months)?;
6424 i64::try_from(i128::from(moved) * i128::from(DAY) + i128::from(nanos.rem_euclid(DAY))).ok()
6425}
6426
6427#[must_use]
6432pub fn add_calendar_months_days(day: i64, months: i64) -> Option<i64> {
6433 if day.unsigned_abs() > 365_000_000 {
6436 return None;
6437 }
6438 let (year, month, day) = civil_from_days(day);
6439 let total = year
6440 .checked_mul(12)?
6441 .checked_add(i64::from(month) - 1)?
6442 .checked_add(months)?;
6443 let year = total.div_euclid(12);
6444 if year.unsigned_abs() > 1_000_000 {
6445 return None;
6446 }
6447 let month = u32::try_from(total.rem_euclid(12)).ok()? + 1;
6448 let day = day.min(days_in_month(year, month)?);
6449 Some(days_from_civil(year, month, day))
6450}
6451
6452fn days_from_civil(year: i64, month: u32, day: u32) -> i64 {
6456 let (month, day) = (i64::from(month), i64::from(day));
6457 let year = if month <= 2 { year - 1 } else { year };
6458 let era = if year >= 0 { year } else { year - 399 } / 400;
6459 let yoe = year - era * 400;
6460 let doy = (153 * ((month + 9) % 12) + 2) / 5 + day - 1;
6461 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
6462 era * 146_097 + doe - 719_468
6463}
6464
6465fn days_in_month(year: i64, month: u32) -> Option<u32> {
6474 if !(1..=12).contains(&month) {
6475 return None;
6476 }
6477 let is_leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
6478 let days: [u32; 12] = [
6479 31,
6480 if is_leap { 29 } else { 28 },
6481 31,
6482 30,
6483 31,
6484 30,
6485 31,
6486 31,
6487 30,
6488 31,
6489 30,
6490 31,
6491 ];
6492 Some(days[(month - 1) as usize])
6493}
6494
6495fn iso_weeks_in_year(year: i64) -> i64 {
6502 fn p(y: i64) -> i64 {
6503 (y + y.div_euclid(4) - y.div_euclid(100) + y.div_euclid(400)).rem_euclid(7)
6504 }
6505 if p(year) == 4 || p(year - 1) == 3 {
6506 53
6507 } else {
6508 52
6509 }
6510}
6511
6512#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
6518pub struct Timestamp {
6519 pub nanos: i64,
6521 #[serde(default, skip_serializing_if = "Option::is_none")]
6525 pub tz: Option<String>,
6526}
6527
6528#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
6549pub enum TimedeltaStringResolution {
6550 Days,
6552 Full,
6554}
6555
6556#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
6576pub enum DatetimeStringResolution {
6577 Date,
6579 Second,
6581 Milli,
6583 Micro,
6585 Nano,
6587}
6588
6589impl Timestamp {
6590 pub const NAT: i64 = i64::MIN;
6592
6593 #[must_use]
6596 pub const fn from_nanos(nanos: i64) -> Self {
6597 Self { nanos, tz: None }
6598 }
6599
6600 #[must_use]
6605 pub fn from_nanos_tz(nanos: i64, tz_name: impl Into<String>) -> Self {
6606 Self {
6607 nanos,
6608 tz: Some(tz_name.into()),
6609 }
6610 }
6611
6612 #[must_use]
6628 pub fn now() -> Self {
6629 use std::time::{SystemTime, UNIX_EPOCH};
6630 let duration = SystemTime::now()
6631 .duration_since(UNIX_EPOCH)
6632 .unwrap_or_default();
6633 let nanos = duration.as_nanos() as i64;
6634 Self { nanos, tz: None }
6635 }
6636
6637 #[must_use]
6639 pub fn utcnow() -> Self {
6640 Self::now()
6641 }
6642
6643 #[must_use]
6647 pub fn today() -> Self {
6648 let now = Self::now();
6649 now.normalize()
6650 }
6651
6652 #[must_use]
6654 pub const fn nat() -> Self {
6655 Self {
6656 nanos: Self::NAT,
6657 tz: None,
6658 }
6659 }
6660
6661 #[must_use]
6663 pub const fn is_nat(&self) -> bool {
6664 self.nanos == Self::NAT
6665 }
6666
6667 #[must_use]
6669 pub const fn value(&self) -> i64 {
6670 self.nanos
6671 }
6672
6673 #[must_use]
6678 pub const fn unit(&self) -> Option<&'static str> {
6679 if self.is_nat() { None } else { Some("ns") }
6680 }
6681
6682 #[must_use]
6686 pub const fn resolution(&self) -> Option<&'static str> {
6687 if self.is_nat() { None } else { Some("ns") }
6688 }
6689
6690 #[must_use]
6692 pub const fn asm8(&self) -> i64 {
6693 self.value()
6694 }
6695
6696 #[must_use]
6698 pub const fn to_datetime64(&self) -> i64 {
6699 self.value()
6700 }
6701
6702 #[must_use]
6704 pub const fn to_numpy(&self) -> i64 {
6705 self.value()
6706 }
6707
6708 pub fn timestamp(&self) -> Result<f64, TypeError> {
6714 if self.is_nat() {
6715 return Err(TypeError::ValueIsMissing {
6716 kind: NullKind::NaT,
6717 });
6718 }
6719 let seconds = self.nanos as f64 / 1_000_000_000.0;
6720 let rounded = format!("{seconds:.6}").parse().unwrap_or(seconds);
6721 Ok(rounded)
6722 }
6723
6724 #[must_use]
6732 pub fn add_timedelta(&self, td_nanos: i64) -> Self {
6733 self.try_add_timedelta(td_nanos)
6734 .unwrap_or_else(|_| Self::nat())
6735 }
6736
6737 pub fn try_add_timedelta(&self, td_nanos: i64) -> Result<Self, TemporalFailure> {
6748 if self.is_nat() || td_nanos == Timedelta::NAT {
6749 return Ok(Self::nat());
6750 }
6751 match self.nanos.checked_add(td_nanos) {
6752 Some(nanos) => Ok(Self {
6753 nanos,
6754 tz: self.tz.clone(),
6755 }),
6756 None => Err(TemporalFailure::new(
6760 "Timestamp::add_timedelta",
6761 PandasTemporalError::OutOfBoundsDatetime,
6762 )
6763 .with_operands(self.nanos, td_nanos)),
6764 }
6765 }
6766
6767 #[must_use]
6769 pub fn sub_timedelta(&self, td_nanos: i64) -> Self {
6770 self.try_sub_timedelta(td_nanos)
6771 .unwrap_or_else(|_| Self::nat())
6772 }
6773
6774 pub fn try_sub_timedelta(&self, td_nanos: i64) -> Result<Self, TemporalFailure> {
6780 if self.is_nat() || td_nanos == Timedelta::NAT {
6781 return Ok(Self::nat());
6782 }
6783 match self.nanos.checked_sub(td_nanos) {
6784 Some(nanos) => Ok(Self {
6785 nanos,
6786 tz: self.tz.clone(),
6787 }),
6788 None => Err(TemporalFailure::new(
6789 "Timestamp::sub_timedelta",
6790 PandasTemporalError::OutOfBoundsDatetime,
6791 )
6792 .with_operands(self.nanos, td_nanos)),
6793 }
6794 }
6795
6796 #[must_use]
6800 pub fn sub_timestamp(&self, other: &Self) -> i64 {
6801 self.try_sub_timestamp(other).unwrap_or(Timedelta::NAT)
6802 }
6803
6804 pub fn try_sub_timestamp(&self, other: &Self) -> Result<i64, TemporalFailure> {
6810 if self.is_nat() || other.is_nat() {
6811 return Ok(Timedelta::NAT);
6812 }
6813 self.nanos.checked_sub(other.nanos).ok_or(
6814 TemporalFailure::new(
6815 "Timestamp::sub_timestamp",
6816 PandasTemporalError::OutOfBoundsDatetime,
6817 )
6818 .with_operands(self.nanos, other.nanos),
6819 )
6820 }
6821
6822 #[must_use]
6827 pub fn semantic_eq(&self, other: &Self) -> bool {
6828 if self.is_nat() && other.is_nat() {
6829 return true;
6830 }
6831 if self.is_nat() || other.is_nat() {
6832 return false;
6833 }
6834 self.nanos == other.nanos && self.tz == other.tz
6835 }
6836
6837 #[must_use]
6850 pub fn floor_to(&self, unit_nanos: i64) -> Self {
6851 if self.is_nat() || unit_nanos <= 0 {
6852 return Self::nat();
6853 }
6854 let Some(nanos) = self.nanos.div_euclid(unit_nanos).checked_mul(unit_nanos) else {
6855 return Self::nat();
6856 };
6857 Self {
6858 nanos,
6859 tz: self.tz.clone(),
6860 }
6861 }
6862
6863 #[must_use]
6868 pub fn ceil_to(&self, unit_nanos: i64) -> Self {
6869 if self.is_nat() || unit_nanos <= 0 {
6870 return Self::nat();
6871 }
6872 let rem = self.nanos.rem_euclid(unit_nanos);
6873 let nanos = if rem == 0 {
6874 self.nanos
6875 } else {
6876 let Some(nanos) = self.nanos.checked_add(unit_nanos - rem) else {
6881 return Self::nat();
6882 };
6883 nanos
6884 };
6885 Self {
6886 nanos,
6887 tz: self.tz.clone(),
6888 }
6889 }
6890
6891 #[must_use]
6897 pub fn round_to(&self, unit_nanos: i64) -> Self {
6898 if self.is_nat() || unit_nanos <= 0 {
6899 return Self::nat();
6900 }
6901 let floor = self.nanos.div_euclid(unit_nanos);
6902 let rem = self.nanos.rem_euclid(unit_nanos);
6903 let half = unit_nanos / 2;
6904 let chosen_floor = if rem < half {
6905 floor
6906 } else if rem > half {
6907 floor + 1
6908 } else if unit_nanos % 2 != 0 {
6909 floor + 1
6911 } else {
6912 if floor % 2 == 0 { floor } else { floor + 1 }
6914 };
6915 let Some(nanos) = chosen_floor.checked_mul(unit_nanos) else {
6919 return Self::nat();
6920 };
6921 Self {
6922 nanos,
6923 tz: self.tz.clone(),
6924 }
6925 }
6926
6927 fn fixed_freq_nanos(freq: &str) -> Option<i64> {
6939 Timedelta::unit_to_nanos(freq).or_else(|| Timedelta::parse(freq).ok())
6940 }
6941
6942 #[must_use]
6946 pub fn floor_to_unit(&self, unit: &str) -> Self {
6947 match Self::fixed_freq_nanos(unit) {
6948 Some(unit_nanos) => self.floor_to(unit_nanos),
6949 None => Self::nat(),
6950 }
6951 }
6952
6953 #[must_use]
6957 pub fn ceil_to_unit(&self, unit: &str) -> Self {
6958 match Self::fixed_freq_nanos(unit) {
6959 Some(unit_nanos) => self.ceil_to(unit_nanos),
6960 None => Self::nat(),
6961 }
6962 }
6963
6964 #[must_use]
6968 pub fn round_to_unit(&self, unit: &str) -> Self {
6969 match Self::fixed_freq_nanos(unit) {
6970 Some(unit_nanos) => self.round_to(unit_nanos),
6971 None => Self::nat(),
6972 }
6973 }
6974
6975 #[must_use]
6977 pub fn floor(&self, freq: &str) -> Self {
6978 self.floor_to_unit(freq)
6979 }
6980
6981 #[must_use]
6983 pub fn ceil(&self, freq: &str) -> Self {
6984 self.ceil_to_unit(freq)
6985 }
6986
6987 #[must_use]
6989 pub fn round(&self, freq: &str) -> Self {
6990 self.round_to_unit(freq)
6991 }
6992
6993 #[must_use]
6997 pub fn year(&self) -> Option<i64> {
6998 if self.is_nat() {
6999 return None;
7000 }
7001 let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
7005 let days = days_since_epoch + 719_468;
7006 let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
7007 let doe = days - era * 146_097;
7008 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
7009 let y = yoe + era * 400;
7010 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
7011 let mp = (5 * doy + 2) / 153;
7012 let m = if mp < 10 { mp + 3 } else { mp - 9 };
7013 Some(if m <= 2 { y + 1 } else { y })
7014 }
7015
7016 #[must_use]
7020 pub fn month(&self) -> Option<i64> {
7021 if self.is_nat() {
7022 return None;
7023 }
7024 let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
7028 let days = days_since_epoch + 719_468;
7029 let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
7030 let doe = days - era * 146_097;
7031 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
7032 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
7033 let mp = (5 * doy + 2) / 153;
7034 Some(if mp < 10 { mp + 3 } else { mp - 9 })
7035 }
7036
7037 #[must_use]
7041 pub fn day(&self) -> Option<i64> {
7042 if self.is_nat() {
7043 return None;
7044 }
7045 let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
7049 let days = days_since_epoch + 719_468;
7050 let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
7051 let doe = days - era * 146_097;
7052 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
7053 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
7054 let mp = (5 * doy + 2) / 153;
7055 Some(doy - (153 * mp + 2) / 5 + 1)
7056 }
7057
7058 #[must_use]
7062 pub fn hour(&self) -> Option<i64> {
7063 if self.is_nat() {
7064 return None;
7065 }
7066 let secs_of_day =
7070 self.nanos.rem_euclid(Timedelta::NANOS_PER_DAY) / Timedelta::NANOS_PER_SEC;
7071 Some(secs_of_day / 3600)
7072 }
7073
7074 #[must_use]
7078 pub fn minute(&self) -> Option<i64> {
7079 if self.is_nat() {
7080 return None;
7081 }
7082 let secs_of_day =
7086 self.nanos.rem_euclid(Timedelta::NANOS_PER_DAY) / Timedelta::NANOS_PER_SEC;
7087 Some((secs_of_day % 3600) / 60)
7088 }
7089
7090 #[must_use]
7094 pub fn second(&self) -> Option<i64> {
7095 if self.is_nat() {
7096 return None;
7097 }
7098 let secs_of_day =
7102 self.nanos.rem_euclid(Timedelta::NANOS_PER_DAY) / Timedelta::NANOS_PER_SEC;
7103 Some(secs_of_day % 60)
7104 }
7105
7106 #[must_use]
7110 pub fn microsecond(&self) -> Option<i64> {
7111 if self.is_nat() {
7112 return None;
7113 }
7114 let sub_nanos = self.nanos.rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
7117 Some((sub_nanos / 1000) as i64)
7118 }
7119
7120 #[must_use]
7124 pub fn nanosecond(&self) -> Option<i64> {
7125 if self.is_nat() {
7126 return None;
7127 }
7128 let sub_nanos = self.nanos.rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
7131 Some((sub_nanos % 1000) as i64)
7132 }
7133
7134 #[must_use]
7138 pub fn dayofweek(&self) -> Option<i64> {
7139 if self.is_nat() {
7140 return None;
7141 }
7142 let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
7144 let dow = ((days_since_epoch + 3) % 7 + 7) % 7;
7145 Some(dow)
7146 }
7147
7148 #[must_use]
7150 pub fn weekday(&self) -> Option<i64> {
7151 self.dayofweek()
7152 }
7153
7154 #[must_use]
7156 pub fn day_of_week(&self) -> Option<i64> {
7157 self.dayofweek()
7158 }
7159
7160 #[must_use]
7164 pub fn dayofyear(&self) -> Option<i64> {
7165 if self.is_nat() {
7166 return None;
7167 }
7168 let m = self.month()?;
7169 let d = self.day()?;
7170 let y = self.year()?;
7171 let is_leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
7172 let days_before: [i64; 12] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
7173 let base = days_before[(m - 1) as usize] + d;
7174 if is_leap && m > 2 {
7175 Some(base + 1)
7176 } else {
7177 Some(base)
7178 }
7179 }
7180
7181 #[must_use]
7183 pub fn day_of_year(&self) -> Option<i64> {
7184 self.dayofyear()
7185 }
7186
7187 #[must_use]
7191 pub fn toordinal(&self) -> Option<i64> {
7192 if self.is_nat() {
7193 return None;
7194 }
7195 let y = self.year()?;
7196 let m = self.month()?;
7197 let d = self.day()?;
7198 let y_minus_1 = y - 1;
7202 let mut ordinal = y_minus_1 * 365 + y_minus_1 / 4 - y_minus_1 / 100 + y_minus_1 / 400;
7203 let is_leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
7204 let days_before: [i64; 12] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
7205 ordinal += days_before[(m - 1) as usize];
7206 if is_leap && m > 2 {
7207 ordinal += 1;
7208 }
7209 ordinal += d;
7210 Some(ordinal)
7211 }
7212
7213 #[must_use]
7217 pub fn fromordinal(ordinal: i64) -> Self {
7218 if ordinal <= 0 {
7219 return Self {
7220 nanos: Self::NAT,
7221 tz: None,
7222 };
7223 }
7224 let days_since_epoch = ordinal - 719163;
7227 match days_since_epoch.checked_mul(Timedelta::NANOS_PER_DAY) {
7228 Some(nanos) => Self { nanos, tz: None },
7229 None => Self::nat(),
7230 }
7231 }
7232
7233 #[must_use]
7239 pub fn to_julian_date(&self) -> f64 {
7240 if self.is_nat() {
7241 return f64::NAN;
7242 }
7243 let ordinal = match self.toordinal() {
7247 Some(o) => o,
7248 None => return f64::NAN,
7249 };
7250 let h = self.hour().unwrap_or(0) as f64;
7252 let m = self.minute().unwrap_or(0) as f64;
7253 let s = self.second().unwrap_or(0) as f64;
7254 let us = self.microsecond().unwrap_or(0) as f64;
7255 let ns = self.nanosecond().unwrap_or(0) as f64;
7256 let frac_day =
7257 (h + m / 60.0 + s / 3600.0 + us / 3_600_000_000.0 + ns / 3_600_000_000_000.0) / 24.0;
7258 1721424.5 + ordinal as f64 + frac_day
7260 }
7261
7262 #[must_use]
7266 pub fn quarter(&self) -> Option<i64> {
7267 self.month().map(|m| (m - 1) / 3 + 1)
7268 }
7269
7270 #[must_use]
7274 pub fn weekofyear(&self) -> Option<i64> {
7275 if self.is_nat() {
7276 return None;
7277 }
7278 let doy = self.dayofyear()?;
7279 let dow = self.dayofweek()?;
7280 let year = self.year()?;
7281 let iso_dow = if dow == 6 { 7 } else { dow + 1 };
7282 let week = (doy - iso_dow + 10) / 7;
7283 if week < 1 {
7289 Some(iso_weeks_in_year(year - 1))
7290 } else if week > iso_weeks_in_year(year) {
7291 Some(1)
7292 } else {
7293 Some(week)
7294 }
7295 }
7296
7297 #[must_use]
7299 pub fn week(&self) -> Option<i64> {
7300 self.weekofyear()
7301 }
7302
7303 #[must_use]
7308 pub fn to_unit(&self, unit: &str) -> Option<i64> {
7309 if self.is_nat() {
7310 return None;
7311 }
7312 match unit {
7313 "ns" | "nanosecond" | "nanoseconds" => Some(self.nanos),
7314 "us" | "microsecond" | "microseconds" => Some(self.nanos / 1_000),
7315 "ms" | "millisecond" | "milliseconds" => Some(self.nanos / 1_000_000),
7316 "s" | "second" | "seconds" => Some(self.nanos / 1_000_000_000),
7317 _ => None,
7318 }
7319 }
7320
7321 #[must_use]
7325 pub fn is_leap_year(&self) -> Option<bool> {
7326 self.year()
7327 .map(|y| (y % 4 == 0 && y % 100 != 0) || y % 400 == 0)
7328 }
7329
7330 #[must_use]
7334 pub fn is_month_start(&self) -> Option<bool> {
7335 self.day().map(|d| d == 1)
7336 }
7337
7338 #[must_use]
7342 pub fn is_month_end(&self) -> Option<bool> {
7343 let y = self.year()?;
7344 let m = self.month()?;
7345 let d = self.day()?;
7346 let is_leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
7347 let days_in_month: [i64; 12] = [
7348 31,
7349 if is_leap { 29 } else { 28 },
7350 31,
7351 30,
7352 31,
7353 30,
7354 31,
7355 31,
7356 30,
7357 31,
7358 30,
7359 31,
7360 ];
7361 Some(d == days_in_month[(m - 1) as usize])
7362 }
7363
7364 #[must_use]
7368 pub fn is_quarter_start(&self) -> Option<bool> {
7369 let m = self.month()?;
7370 let d = self.day()?;
7371 Some(d == 1 && (m == 1 || m == 4 || m == 7 || m == 10))
7372 }
7373
7374 #[must_use]
7378 pub fn is_quarter_end(&self) -> Option<bool> {
7379 let m = self.month()?;
7380 let d = self.day()?;
7381 Some(
7382 (m == 3 && d == 31)
7383 || (m == 6 && d == 30)
7384 || (m == 9 && d == 30)
7385 || (m == 12 && d == 31),
7386 )
7387 }
7388
7389 #[must_use]
7393 pub fn is_year_start(&self) -> Option<bool> {
7394 let m = self.month()?;
7395 let d = self.day()?;
7396 Some(m == 1 && d == 1)
7397 }
7398
7399 #[must_use]
7403 pub fn is_year_end(&self) -> Option<bool> {
7404 let m = self.month()?;
7405 let d = self.day()?;
7406 Some(m == 12 && d == 31)
7407 }
7408
7409 #[must_use]
7413 pub fn days_in_month(&self) -> Option<i64> {
7414 let y = self.year()?;
7415 let m = self.month()?;
7416 let is_leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
7417 let days: [i64; 12] = [
7418 31,
7419 if is_leap { 29 } else { 28 },
7420 31,
7421 30,
7422 31,
7423 30,
7424 31,
7425 31,
7426 30,
7427 31,
7428 30,
7429 31,
7430 ];
7431 Some(days[(m - 1) as usize])
7432 }
7433
7434 #[must_use]
7436 pub fn daysinmonth(&self) -> Option<i64> {
7437 self.days_in_month()
7438 }
7439
7440 #[must_use]
7442 pub fn normalize(&self) -> Self {
7443 self.floor_to(Timedelta::NANOS_PER_DAY)
7444 }
7445
7446 #[must_use]
7450 #[allow(clippy::too_many_arguments)]
7451 pub fn replace(
7452 &self,
7453 year: Option<i64>,
7454 month: Option<i64>,
7455 day: Option<i64>,
7456 hour: Option<i64>,
7457 minute: Option<i64>,
7458 second: Option<i64>,
7459 microsecond: Option<i64>,
7460 nanosecond: Option<i64>,
7461 ) -> Self {
7462 if self.is_nat() {
7463 return self.clone();
7464 }
7465 let cur_year = self.year().unwrap_or(1970);
7466 let cur_month = self.month().unwrap_or(1);
7467 let cur_day = self.day().unwrap_or(1);
7468 let cur_hour = self.hour().unwrap_or(0);
7469 let cur_minute = self.minute().unwrap_or(0);
7470 let cur_second = self.second().unwrap_or(0);
7471 let cur_micro = self.microsecond().unwrap_or(0);
7472 let cur_nano = self.nanosecond().unwrap_or(0);
7473
7474 let y = year.unwrap_or(cur_year);
7475 let mo = month.unwrap_or(cur_month);
7476 let d = day.unwrap_or(cur_day);
7477 let h = hour.unwrap_or(cur_hour);
7478 let mi = minute.unwrap_or(cur_minute);
7479 let s = second.unwrap_or(cur_second);
7480 let us = microsecond.unwrap_or(cur_micro);
7481 let ns = nanosecond.unwrap_or(cur_nano);
7482
7483 if !(1..=12).contains(&mo)
7484 || !(1..=days_in_month(y, mo as u32).unwrap_or(0) as i64).contains(&d)
7485 || !(0..=23).contains(&h)
7486 || !(0..=59).contains(&mi)
7487 || !(0..=59).contains(&s)
7488 || !(0..=999_999).contains(&us)
7489 || !(0..=999).contains(&ns)
7490 {
7491 return Self::nat();
7492 }
7493
7494 let days_from_epoch = Self::days_from_ymd(y, mo, d);
7506 let secs = h * 3600 + mi * 60 + s;
7507 let Some(total_nanos) = days_from_epoch
7508 .checked_mul(Timedelta::NANOS_PER_DAY)
7509 .and_then(|nanos| {
7510 secs.checked_mul(Timedelta::NANOS_PER_SEC)
7511 .and_then(|s_nanos| nanos.checked_add(s_nanos))
7512 })
7513 .and_then(|nanos| {
7514 us.checked_mul(Timedelta::NANOS_PER_MICRO)
7515 .and_then(|us_nanos| nanos.checked_add(us_nanos))
7516 })
7517 .and_then(|nanos| nanos.checked_add(ns))
7518 else {
7519 return Self::nat();
7520 };
7521
7522 Self {
7523 nanos: total_nanos,
7524 tz: self.tz.clone(),
7525 }
7526 }
7527
7528 fn days_from_ymd(year: i64, month: i64, day: i64) -> i64 {
7529 let y = if month <= 2 { year - 1 } else { year };
7530 let era = if y >= 0 { y } else { y - 399 } / 400;
7531 let yoe = y - era * 400;
7532 let doy = (153 * (if month > 2 { month - 3 } else { month + 9 }) + 2) / 5 + day - 1;
7533 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
7534 era * 146097 + doe - 719468
7535 }
7536
7537 #[must_use]
7541 pub fn isoformat(&self) -> String {
7542 use std::fmt::Write as _;
7543
7544 if self.is_nat() {
7545 return "NaT".to_string();
7546 }
7547 let display_nanos = self
7548 .tz
7549 .as_deref()
7550 .and_then(Self::fixed_utc_offset_seconds)
7551 .and_then(|offset| self.nanos.checked_add(offset * Timedelta::NANOS_PER_SEC))
7552 .unwrap_or(self.nanos);
7553 let days_since_epoch = display_nanos.div_euclid(Timedelta::NANOS_PER_DAY);
7556 let nanos_of_day = display_nanos.rem_euclid(Timedelta::NANOS_PER_DAY);
7557 let secs_of_day = nanos_of_day / Timedelta::NANOS_PER_SEC;
7558 let sub_nanos = nanos_of_day.rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
7559
7560 let days = days_since_epoch + 719_468;
7561 let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
7562 let doe = days - era * 146_097;
7563 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
7564 let y = yoe + era * 400;
7565 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
7566 let mp = (5 * doy + 2) / 153;
7567 let d = doy - (153 * mp + 2) / 5 + 1;
7568 let m = if mp < 10 { mp + 3 } else { mp - 9 };
7569 let year = if m <= 2 { y + 1 } else { y };
7570
7571 let hour = secs_of_day / 3600;
7572 let minute = (secs_of_day % 3600) / 60;
7573 let second = secs_of_day % 60;
7574
7575 let suffix_capacity = self
7579 .tz
7580 .as_ref()
7581 .map_or(0, |tz| if tz == "UTC" { 6 } else { tz.len() + 2 });
7582 let mut result = String::with_capacity(29 + suffix_capacity);
7583 if sub_nanos == 0 {
7584 let _ = write!(
7585 result,
7586 "{year:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02}"
7587 );
7588 } else if sub_nanos.is_multiple_of(1_000) {
7589 let _ = write!(
7590 result,
7591 "{year:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02}.{:06}",
7592 sub_nanos / 1_000
7593 );
7594 } else {
7595 let _ = write!(
7596 result,
7597 "{year:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02}.{sub_nanos:09}"
7598 );
7599 }
7600 match &self.tz {
7601 Some(tz) if tz == "UTC" => result.push_str("+00:00"),
7602 Some(tz) if Self::fixed_utc_offset_seconds(tz).is_some() => {
7603 result.push_str(tz.strip_prefix("UTC").unwrap_or(tz));
7604 }
7605 Some(tz) => {
7606 result.push('[');
7607 result.push_str(tz);
7608 result.push(']');
7609 }
7610 None => {}
7611 }
7612 result
7613 }
7614
7615 #[must_use]
7617 pub fn to_iso8601(&self) -> String {
7618 self.isoformat()
7619 }
7620
7621 #[must_use]
7630 pub const fn string_resolution(nanos: i64) -> DatetimeStringResolution {
7631 if nanos == Self::NAT {
7632 return DatetimeStringResolution::Date;
7633 }
7634 if nanos.rem_euclid(Timedelta::NANOS_PER_DAY) == 0 {
7635 DatetimeStringResolution::Date
7636 } else if nanos.rem_euclid(Timedelta::NANOS_PER_SEC) == 0 {
7637 DatetimeStringResolution::Second
7638 } else if nanos.rem_euclid(Timedelta::NANOS_PER_MILLI) == 0 {
7639 DatetimeStringResolution::Milli
7640 } else if nanos.rem_euclid(Timedelta::NANOS_PER_MICRO) == 0 {
7641 DatetimeStringResolution::Micro
7642 } else {
7643 DatetimeStringResolution::Nano
7644 }
7645 }
7646
7647 #[must_use]
7667 pub fn format_at_resolution(nanos: i64, resolution: DatetimeStringResolution) -> String {
7668 use std::fmt::Write as _;
7669
7670 if nanos == Self::NAT {
7671 return "NaT".to_string();
7672 }
7673 let days_since_epoch = nanos.div_euclid(Timedelta::NANOS_PER_DAY);
7678 let nanos_of_day = nanos.rem_euclid(Timedelta::NANOS_PER_DAY);
7679 let secs_of_day = nanos_of_day / Timedelta::NANOS_PER_SEC;
7680 let sub_nanos = nanos_of_day.rem_euclid(Timedelta::NANOS_PER_SEC);
7681 let (year, month, day) = civil_from_days(days_since_epoch);
7684
7685 let mut result = String::with_capacity(30);
7688 let _ = write!(result, "{year:04}-{month:02}-{day:02}");
7690 if matches!(resolution, DatetimeStringResolution::Date) {
7691 return result;
7692 }
7693 let _ = write!(
7694 result,
7695 " {:02}:{:02}:{:02}",
7696 secs_of_day / 3600,
7697 (secs_of_day % 3600) / 60,
7698 secs_of_day % 60
7699 );
7700 let (fraction, width) = match resolution {
7701 DatetimeStringResolution::Date | DatetimeStringResolution::Second => return result,
7702 DatetimeStringResolution::Milli => (sub_nanos / Timedelta::NANOS_PER_MILLI, 3_usize),
7703 DatetimeStringResolution::Micro => (sub_nanos / Timedelta::NANOS_PER_MICRO, 6_usize),
7704 DatetimeStringResolution::Nano => (sub_nanos, 9_usize),
7705 };
7706 let _ = write!(result, ".{fraction:0width$}", width = width);
7707 result
7708 }
7709
7710 pub fn parse(s: &str) -> Result<Self, TypeError> {
7723 let s = s.trim();
7724
7725 if s.eq_ignore_ascii_case("nat") {
7726 return Ok(Self::nat());
7727 }
7728
7729 let Some((datetime_part, tz)) = Self::split_timezone(s) else {
7730 return Err(TypeError::ValueNotParseable {
7731 value: s.to_string(),
7732 target: "Timestamp".to_string(),
7733 });
7734 };
7735
7736 let (date_part, time_part) = if datetime_part.contains('T') {
7737 datetime_part
7738 .split_once('T')
7739 .ok_or_else(|| TypeError::ValueNotParseable {
7740 value: s.to_string(),
7741 target: "Timestamp".to_string(),
7742 })?
7743 } else if datetime_part.contains(' ')
7744 && datetime_part.chars().filter(|&c| c == ' ').count() == 1
7745 {
7746 datetime_part
7747 .split_once(' ')
7748 .ok_or_else(|| TypeError::ValueNotParseable {
7749 value: s.to_string(),
7750 target: "Timestamp".to_string(),
7751 })?
7752 } else {
7753 (datetime_part, "00:00:00")
7754 };
7755
7756 let (year, month, day) =
7757 Self::parse_date(date_part).ok_or_else(|| TypeError::ValueNotParseable {
7758 value: s.to_string(),
7759 target: "Timestamp".to_string(),
7760 })?;
7761
7762 let (hour, minute, second, nanos) =
7763 Self::parse_time(time_part).ok_or_else(|| TypeError::ValueNotParseable {
7764 value: s.to_string(),
7765 target: "Timestamp".to_string(),
7766 })?;
7767
7768 let wall_nanos = Self::ymd_hms_to_nanos(year, month, day, hour, minute, second, nanos)
7771 .ok_or_else(|| TypeError::ValueNotParseable {
7772 value: s.to_string(),
7773 target: "Timestamp".to_string(),
7774 })?;
7775 let offset = tz
7779 .as_deref()
7780 .and_then(Self::fixed_utc_offset_seconds)
7781 .unwrap_or(0);
7782 let total_nanos = offset
7783 .checked_mul(1_000_000_000)
7784 .and_then(|offset| wall_nanos.checked_sub(offset))
7785 .ok_or_else(|| TypeError::ValueNotParseable {
7786 value: s.to_string(),
7787 target: "Timestamp".to_string(),
7788 })?;
7789
7790 Ok(if let Some(tz_name) = tz {
7791 Self::from_nanos_tz(total_nanos, tz_name)
7792 } else {
7793 Self::from_nanos(total_nanos)
7794 })
7795 }
7796
7797 fn split_timezone(s: &str) -> Option<(&str, Option<String>)> {
7798 if let Some(stripped) = s.strip_suffix('Z') {
7799 Some((stripped, Some("UTC".to_string())))
7800 } else if let Some(idx) = s.rfind('+') {
7801 if idx > 10 && Self::is_timezone_offset(&s[idx..]) {
7802 Some((&s[..idx], Some(s[idx..].to_string())))
7803 } else if idx > 10 {
7804 None
7805 } else {
7806 Some((s, None))
7807 }
7808 } else if let Some(idx) = s.rfind('-') {
7809 if idx > 10 && Self::is_timezone_offset(&s[idx..]) {
7810 Some((&s[..idx], Some(s[idx..].to_string())))
7811 } else if idx > 10 {
7812 None
7813 } else {
7814 Some((s, None))
7815 }
7816 } else {
7817 Some((s, None))
7818 }
7819 }
7820
7821 fn fixed_utc_offset_seconds(tz: &str) -> Option<i64> {
7822 if tz == "UTC" {
7823 return Some(0);
7824 }
7825 let offset = tz.strip_prefix("UTC").unwrap_or(tz);
7826 if !Self::is_timezone_offset(offset) {
7827 return None;
7828 }
7829 let sign = if offset.starts_with('+') { 1 } else { -1 };
7830 let hours = offset[1..3].parse::<i64>().ok()?;
7831 let minutes = offset[4..6].parse::<i64>().ok()?;
7832 Some(sign * (hours * 3_600 + minutes * 60))
7833 }
7834
7835 fn is_timezone_offset(s: &str) -> bool {
7836 let bytes = s.as_bytes();
7837 if bytes.len() != 6 || !matches!(bytes[0], b'+' | b'-') || bytes[3] != b':' {
7838 return false;
7839 }
7840 if !bytes[1..3].iter().all(u8::is_ascii_digit)
7841 || !bytes[4..6].iter().all(u8::is_ascii_digit)
7842 {
7843 return false;
7844 }
7845 let hour = u32::from(bytes[1] - b'0') * 10 + u32::from(bytes[2] - b'0');
7846 let minute = u32::from(bytes[4] - b'0') * 10 + u32::from(bytes[5] - b'0');
7847 hour <= 23 && minute <= 59
7848 }
7849
7850 fn parse_date(s: &str) -> Option<(i64, u32, u32)> {
7851 let parts: Vec<&str> = s.split('-').collect();
7852 if parts.len() != 3 {
7853 return None;
7854 }
7855 let year: i64 = parts[0].parse().ok()?;
7856 let month: u32 = parts[1].parse().ok()?;
7857 let day: u32 = parts[2].parse().ok()?;
7858 if !(1..=days_in_month(year, month)?).contains(&day) {
7859 return None;
7860 }
7861 Some((year, month, day))
7862 }
7863
7864 fn parse_time(s: &str) -> Option<(u32, u32, u32, u64)> {
7865 let (time_str, frac_str) = match s.split_once('.') {
7866 Some((time, frac)) => (time, Some(frac)),
7867 None => (s, None),
7868 };
7869 let parts: Vec<&str> = time_str.split(':').collect();
7870 if parts.is_empty() || parts.len() > 3 {
7871 return None;
7872 }
7873 let hour: u32 = parts.first().and_then(|p| p.parse().ok())?;
7874 let minute: u32 = parts.get(1).and_then(|p| p.parse().ok()).unwrap_or(0);
7875 let second: u32 = parts.get(2).and_then(|p| p.parse().ok()).unwrap_or(0);
7876
7877 if hour > 23 || minute > 59 || second > 59 {
7878 return None;
7879 }
7880
7881 let nanos = match frac_str {
7882 None => 0,
7883 Some(frac) => {
7884 if frac.is_empty() || !frac.bytes().all(|b| b.is_ascii_digit()) {
7885 return None;
7886 }
7887 let digits = frac.len().min(9);
7888 let mut nanos = 0_u64;
7889 for byte in frac.bytes().take(digits) {
7890 nanos = nanos * 10 + u64::from(byte - b'0');
7891 }
7892 for _ in digits..9 {
7893 nanos *= 10;
7894 }
7895 nanos
7896 }
7897 };
7898
7899 Some((hour, minute, second, nanos))
7900 }
7901
7902 fn ymd_hms_to_nanos(
7924 year: i64,
7925 month: u32,
7926 day: u32,
7927 hour: u32,
7928 minute: u32,
7929 second: u32,
7930 sub_nanos: u64,
7931 ) -> Option<i64> {
7932 let m = month as i64;
7933 let d = day as i64;
7934
7935 let y = if m <= 2 { year.checked_sub(1)? } else { year };
7936 let era = if y >= 0 { y } else { y.checked_sub(399)? } / 400;
7937 let yoe = y.checked_sub(era.checked_mul(400)?)?;
7938 let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1;
7939 let doe = yoe
7940 .checked_mul(365)?
7941 .checked_add(yoe / 4 - yoe / 100)?
7942 .checked_add(doy)?;
7943 let days_since_epoch = era
7944 .checked_mul(146_097)?
7945 .checked_add(doe)?
7946 .checked_sub(719_468)?;
7947
7948 let total_seconds = days_since_epoch
7949 .checked_mul(86400)?
7950 .checked_add(i64::from(hour) * 3600)?
7951 .checked_add(i64::from(minute) * 60)?
7952 .checked_add(i64::from(second))?;
7953 total_seconds
7954 .checked_mul(Timedelta::NANOS_PER_SEC)?
7955 .checked_add(sub_nanos as i64)
7956 }
7957
7958 #[must_use]
7965 pub fn strftime(&self, format: &str) -> String {
7966 if self.is_nat() {
7967 return "NaT".to_string();
7968 }
7969 strftime_in_zone(self.nanos, format, self.tz.as_deref())
7970 }
7971
7972 #[must_use]
7976 pub fn day_name(&self) -> String {
7977 const NAMES: [&str; 7] = [
7978 "Thursday",
7979 "Friday",
7980 "Saturday",
7981 "Sunday",
7982 "Monday",
7983 "Tuesday",
7984 "Wednesday",
7985 ];
7986 if self.is_nat() {
7987 return "NaT".to_string();
7988 }
7989 let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
7995 let dow = ((days_since_epoch % 7) + 7) % 7;
7996 NAMES[dow as usize].to_string()
7997 }
7998
7999 #[must_use]
8003 pub fn month_name(&self) -> String {
8004 const NAMES: [&str; 12] = [
8005 "January",
8006 "February",
8007 "March",
8008 "April",
8009 "May",
8010 "June",
8011 "July",
8012 "August",
8013 "September",
8014 "October",
8015 "November",
8016 "December",
8017 ];
8018 if self.is_nat() {
8019 return "NaT".to_string();
8020 }
8021 let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
8025 let days = days_since_epoch + 719_468;
8026 let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
8027 let doe = days - era * 146_097;
8028 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
8029 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
8030 let mp = (5 * doy + 2) / 153;
8031 let m = if mp < 10 { mp + 3 } else { mp - 9 };
8032 NAMES[(m - 1) as usize].to_string()
8033 }
8034
8035 #[must_use]
8040 pub fn tz_localize(&self, tz: Option<&str>) -> Self {
8041 if self.is_nat() {
8042 return Self::nat();
8043 }
8044 Self {
8045 nanos: self.nanos,
8046 tz: tz.map(String::from),
8047 }
8048 }
8049
8050 #[must_use]
8056 pub fn tz_convert(&self, tz: &str) -> Self {
8057 if self.is_nat() {
8058 return Self::nat();
8059 }
8060 Self {
8061 nanos: self.nanos,
8062 tz: Some(tz.to_string()),
8063 }
8064 }
8065
8066 #[must_use]
8071 pub fn fromtimestamp(ts: f64, tz: Option<&str>) -> Self {
8072 if ts.is_nan() || ts.is_infinite() {
8073 return Self::nat();
8074 }
8075 let nanos_f64 = ts * 1_000_000_000.0;
8076 const MAX_NANOS: f64 = i64::MAX as f64;
8078 const MIN_NANOS: f64 = i64::MIN as f64;
8079 if !(MIN_NANOS..=MAX_NANOS).contains(&nanos_f64) {
8080 return Self::nat();
8081 }
8082 Self {
8083 nanos: nanos_f64 as i64,
8084 tz: tz.map(String::from),
8085 }
8086 }
8087
8088 #[must_use]
8095 pub fn from_millis(ms: i64, tz: Option<&str>) -> Self {
8096 let Some(nanos) = ms.checked_mul(1_000_000) else {
8097 return Self::nat();
8098 };
8099 Self {
8100 nanos,
8101 tz: tz.map(String::from),
8102 }
8103 }
8104
8105 #[must_use]
8109 pub fn from_micros(us: i64, tz: Option<&str>) -> Self {
8110 let Some(nanos) = us.checked_mul(1_000) else {
8111 return Self::nat();
8112 };
8113 Self {
8114 nanos,
8115 tz: tz.map(String::from),
8116 }
8117 }
8118
8119 #[must_use]
8121 pub fn tzinfo(&self) -> Option<&str> {
8122 self.tz.as_deref()
8123 }
8124
8125 #[must_use]
8129 pub fn tzname(&self) -> Option<&str> {
8130 self.tzinfo()
8131 }
8132}
8133
8134impl std::fmt::Display for Timestamp {
8135 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
8138 if self.is_nat() {
8139 return f.write_str("NaT");
8140 }
8141 match &self.tz {
8142 Some(tz) => write!(f, "Timestamp[{}, {}]", self.nanos, tz),
8143 None => write!(f, "Timestamp[{}, UTC]", self.nanos),
8144 }
8145 }
8146}
8147
8148impl PartialOrd for Timestamp {
8149 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
8154 if self.is_nat() || other.is_nat() {
8155 return None;
8156 }
8157 Some(self.nanos.cmp(&other.nanos))
8158 }
8159}
8160
8161pub fn isna(values: &[Scalar]) -> Vec<bool> {
8164 values.iter().map(Scalar::is_missing).collect()
8165}
8166
8167pub fn isnull(values: &[Scalar]) -> Vec<bool> {
8168 isna(values)
8169}
8170
8171pub fn notna(values: &[Scalar]) -> Vec<bool> {
8172 values.iter().map(|v| !v.is_missing()).collect()
8173}
8174
8175pub fn notnull(values: &[Scalar]) -> Vec<bool> {
8176 notna(values)
8177}
8178
8179pub fn count_na(values: &[Scalar]) -> usize {
8180 values.iter().filter(|v| v.is_missing()).count()
8181}
8182
8183pub fn fill_na(values: &[Scalar], fill: &Scalar) -> Vec<Scalar> {
8184 values
8185 .iter()
8186 .map(|v| {
8187 if v.is_missing() {
8188 fill.clone()
8189 } else {
8190 v.clone()
8191 }
8192 })
8193 .collect()
8194}
8195
8196pub fn dropna(values: &[Scalar]) -> Vec<Scalar> {
8197 values.iter().filter(|v| !v.is_missing()).cloned().collect()
8198}
8199
8200fn collect_finite(values: &[Scalar]) -> Vec<f64> {
8203 values
8204 .iter()
8205 .filter(|v| !v.is_missing())
8206 .filter_map(|v| v.to_f64().ok())
8207 .collect()
8208}
8209
8210fn collect_timedelta_ns(values: &[Scalar]) -> Option<(i128, usize)> {
8218 let mut sum: i128 = 0;
8219 let mut count: usize = 0;
8220 let mut saw_timedelta = false;
8221 for v in values {
8222 match v {
8223 Scalar::Timedelta64(ns) => {
8224 saw_timedelta = true;
8225 if v.is_missing() {
8226 continue;
8227 }
8228 sum += i128::from(*ns);
8229 count += 1;
8230 }
8231 _ if v.is_missing() => continue,
8232 _ => return None,
8235 }
8236 }
8237 if saw_timedelta {
8238 Some((sum, count))
8239 } else {
8240 None
8241 }
8242}
8243
8244fn timedelta_ns_to_scalar(ns: i128) -> Scalar {
8263 if ns > i128::from(i64::MAX) || ns <= i128::from(i64::MIN) {
8264 return Scalar::Timedelta64(Timedelta::NAT);
8265 }
8266 Scalar::Timedelta64(ns as i64)
8267}
8268
8269pub fn nansum(values: &[Scalar]) -> Scalar {
8270 if let Some((sum, _)) = collect_timedelta_ns(values) {
8271 return timedelta_ns_to_scalar(sum);
8272 }
8273 let mut sum = 0.0_f64;
8278 for v in values {
8279 if v.is_missing() {
8280 continue;
8281 }
8282 if let Ok(x) = v.to_f64() {
8283 sum += x;
8284 }
8285 }
8286 Scalar::Float64(sum)
8287}
8288
8289#[must_use]
8326pub fn nansum_utf8(values: &[Scalar]) -> Scalar {
8327 let mut out: Option<String> = None;
8328 for v in values {
8329 if v.is_missing() {
8330 continue;
8331 }
8332 if let Scalar::Utf8(part) = v {
8333 out.get_or_insert_with(String::new).push_str(part);
8334 }
8335 }
8336 match out {
8337 Some(joined) => Scalar::Utf8(joined),
8338 None => Scalar::Int64(0),
8340 }
8341}
8342
8343pub fn nanmean(values: &[Scalar]) -> Scalar {
8344 if let Some((sum, count)) = collect_timedelta_ns(values) {
8345 if count == 0 {
8346 return Scalar::Timedelta64(Timedelta::NAT);
8347 }
8348 return timedelta_ns_to_scalar(sum / count as i128);
8351 }
8352 if let Some((sum, count)) = collect_datetime_ns(values) {
8359 if count == 0 {
8360 return Scalar::Datetime64(Timestamp::NAT);
8361 }
8362 let mean = sum / count as i128;
8363 if mean > i128::from(i64::MAX) || mean <= i128::from(i64::MIN) {
8364 return Scalar::Datetime64(Timestamp::NAT);
8365 }
8366 return Scalar::Datetime64(mean as i64);
8367 }
8368 let mut sum = 0.0_f64;
8372 let mut count = 0usize;
8373 for v in values {
8374 if v.is_missing() {
8375 continue;
8376 }
8377 if let Ok(x) = v.to_f64() {
8378 sum += x;
8379 count += 1;
8380 }
8381 }
8382 if count == 0 {
8383 return Scalar::Null(NullKind::NaN);
8384 }
8385 Scalar::Float64(sum / count as f64)
8386}
8387
8388pub fn nanany(values: &[Scalar]) -> Scalar {
8389 for v in values {
8390 if v.is_missing() {
8391 continue;
8392 }
8393 match v {
8394 Scalar::Bool(flag) if *flag => return Scalar::Bool(true),
8395 Scalar::Int64(val) if *val != 0 => return Scalar::Bool(true),
8396 Scalar::Float64(val) if !val.is_nan() && *val != 0.0 => return Scalar::Bool(true),
8397 Scalar::Utf8(val) if !val.is_empty() => return Scalar::Bool(true),
8398 Scalar::Timedelta64(ns) if *ns != 0 => return Scalar::Bool(true),
8401 _ => continue,
8402 }
8403 }
8404 Scalar::Bool(false)
8405}
8406
8407pub fn nanall(values: &[Scalar]) -> Scalar {
8408 for v in values {
8409 if v.is_missing() {
8410 continue;
8411 }
8412 match v {
8413 Scalar::Bool(flag) if !*flag => return Scalar::Bool(false),
8414 Scalar::Int64(val) if *val == 0 => return Scalar::Bool(false),
8415 Scalar::Float64(val) if val.is_nan() || *val == 0.0 => return Scalar::Bool(false),
8416 Scalar::Utf8(val) if val.is_empty() => return Scalar::Bool(false),
8417 Scalar::Timedelta64(ns) if *ns == 0 => return Scalar::Bool(false),
8420 _ => continue,
8421 }
8422 }
8423 Scalar::Bool(true)
8424}
8425
8426pub fn nancount(values: &[Scalar]) -> Scalar {
8427 let n = values.iter().filter(|v| !v.is_missing()).count();
8428 Scalar::Int64(n as i64)
8429}
8430
8431pub fn nanmin(values: &[Scalar]) -> Scalar {
8432 let mut min: Option<&Scalar> = None;
8433 for v in values {
8434 if v.is_missing() {
8435 continue;
8436 }
8437 match (min, v) {
8438 (None, _) => min = Some(v),
8439 (Some(Scalar::Int64(a)), Scalar::Int64(b)) => {
8440 if b < a {
8441 min = Some(v)
8442 }
8443 }
8444 (Some(Scalar::Float64(a)), Scalar::Float64(b)) => {
8445 if *b < *a {
8446 min = Some(v)
8447 }
8448 }
8449 (Some(Scalar::Utf8(a)), Scalar::Utf8(b)) => {
8450 if b < a {
8451 min = Some(v)
8452 }
8453 }
8454 (Some(Scalar::Bool(a)), Scalar::Bool(b)) => {
8455 if b < a {
8456 min = Some(v)
8457 }
8458 }
8459 (Some(Scalar::Timedelta64(a)), Scalar::Timedelta64(b)) => {
8464 if b < a {
8465 min = Some(v)
8466 }
8467 }
8468 (Some(Scalar::Datetime64(a)), Scalar::Datetime64(b)) => {
8473 if b < a {
8474 min = Some(v)
8475 }
8476 }
8477 (Some(Scalar::Period(a)), Scalar::Period(b)) => {
8490 if a.freq != b.freq {
8491 return Scalar::Null(NullKind::NaN);
8492 }
8493 if b.ordinal < a.ordinal {
8494 min = Some(v)
8495 }
8496 }
8497 (Some(Scalar::Interval(a)), Scalar::Interval(b)) => {
8512 if a.left.is_nan() || a.right.is_nan() || b.left.is_nan() || b.right.is_nan() {
8513 return Scalar::Null(NullKind::NaN);
8514 }
8515 if (b.left, b.right) < (a.left, a.right) {
8516 min = Some(v)
8517 }
8518 }
8519 (Some(a), b) => match (a.to_f64(), b.to_f64()) {
8520 (Ok(af), Ok(bf)) if bf < af => min = Some(v),
8521 (Ok(_), Ok(_)) => {}
8522 _ => return Scalar::Null(NullKind::NaN),
8523 },
8524 }
8525 }
8526 match min {
8527 Some(v) => v.clone(),
8528 None => Scalar::Null(NullKind::NaN),
8529 }
8530}
8531
8532pub fn nanmax(values: &[Scalar]) -> Scalar {
8533 let mut max: Option<&Scalar> = None;
8534 for v in values {
8535 if v.is_missing() {
8536 continue;
8537 }
8538 match (max, v) {
8539 (None, _) => max = Some(v),
8540 (Some(Scalar::Int64(a)), Scalar::Int64(b)) => {
8541 if b > a {
8542 max = Some(v)
8543 }
8544 }
8545 (Some(Scalar::Float64(a)), Scalar::Float64(b)) => {
8546 if *b > *a {
8547 max = Some(v)
8548 }
8549 }
8550 (Some(Scalar::Utf8(a)), Scalar::Utf8(b)) => {
8551 if b > a {
8552 max = Some(v)
8553 }
8554 }
8555 (Some(Scalar::Bool(a)), Scalar::Bool(b)) => {
8556 if b > a {
8557 max = Some(v)
8558 }
8559 }
8560 (Some(Scalar::Timedelta64(a)), Scalar::Timedelta64(b)) => {
8564 if b > a {
8565 max = Some(v)
8566 }
8567 }
8568 (Some(Scalar::Datetime64(a)), Scalar::Datetime64(b)) => {
8570 if b > a {
8571 max = Some(v)
8572 }
8573 }
8574 (Some(Scalar::Period(a)), Scalar::Period(b)) => {
8576 if a.freq != b.freq {
8577 return Scalar::Null(NullKind::NaN);
8578 }
8579 if b.ordinal > a.ordinal {
8580 max = Some(v)
8581 }
8582 }
8583 (Some(Scalar::Interval(a)), Scalar::Interval(b)) => {
8586 if a.left.is_nan() || a.right.is_nan() || b.left.is_nan() || b.right.is_nan() {
8587 return Scalar::Null(NullKind::NaN);
8588 }
8589 if (b.left, b.right) > (a.left, a.right) {
8590 max = Some(v)
8591 }
8592 }
8593 (Some(a), b) => match (a.to_f64(), b.to_f64()) {
8594 (Ok(af), Ok(bf)) if bf > af => max = Some(v),
8595 (Ok(_), Ok(_)) => {}
8596 _ => return Scalar::Null(NullKind::NaN),
8597 },
8598 }
8599 }
8600 match max {
8601 Some(v) => v.clone(),
8602 None => Scalar::Null(NullKind::NaN),
8603 }
8604}
8605
8606#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8618enum TemporalFamily {
8619 Timedelta,
8620 Datetime,
8621 Period(PeriodFreq),
8623}
8624
8625impl TemporalFamily {
8626 fn make(self, raw: i64) -> Scalar {
8628 match self {
8629 Self::Timedelta => Scalar::Timedelta64(raw),
8630 Self::Datetime => Scalar::Datetime64(raw),
8631 Self::Period(freq) => Scalar::Period(Period::new(raw, freq)),
8632 }
8633 }
8634
8635 fn nat(self) -> Scalar {
8637 self.make(i64::MIN)
8638 }
8639}
8640
8641fn collect_temporal_backing(values: &[Scalar]) -> Option<(Vec<f64>, TemporalFamily)> {
8656 let mut out = Vec::with_capacity(values.len());
8657 let mut family: Option<TemporalFamily> = None;
8658 for v in values {
8659 let (raw, this) = match v {
8660 Scalar::Timedelta64(ns) => (*ns, TemporalFamily::Timedelta),
8661 Scalar::Datetime64(ns) => (*ns, TemporalFamily::Datetime),
8662 Scalar::Period(p) => (p.ordinal, TemporalFamily::Period(p.freq)),
8663 _ if v.is_missing() => continue,
8664 _ => return None,
8665 };
8666 match family {
8668 Some(existing) if existing != this => return None,
8669 _ => family = Some(this),
8670 }
8671 if v.is_missing() {
8672 continue;
8673 }
8674 out.push(raw as f64);
8675 }
8676 family.map(|f| (out, f))
8677}
8678
8679fn collect_timedelta_ns_f64(values: &[Scalar]) -> Option<Vec<f64>> {
8686 match collect_temporal_backing(values) {
8687 Some((out, TemporalFamily::Timedelta)) => Some(out),
8688 _ => None,
8689 }
8690}
8691
8692fn float_ns_to_timedelta(value: f64) -> Scalar {
8694 float_ns_to_temporal(value, TemporalFamily::Timedelta)
8695}
8696
8697fn float_ns_to_temporal(value: f64, make: TemporalFamily) -> Scalar {
8700 if !value.is_finite() {
8701 return make.nat();
8702 }
8703 let clamped = value.clamp(i64::MIN as f64, i64::MAX as f64);
8704 make.make(clamped as i64)
8705}
8706
8707pub fn nanmedian(values: &[Scalar]) -> Scalar {
8708 let Some((_, make)) = collect_temporal_backing(values) else {
8722 return nanmedian_numeric(values);
8724 };
8725 let mut td: Vec<i64> = values
8726 .iter()
8727 .filter(|value| !value.is_missing())
8728 .filter_map(|value| match value {
8729 Scalar::Timedelta64(ns) | Scalar::Datetime64(ns) => Some(*ns),
8730 Scalar::Period(p) => Some(p.ordinal),
8731 _ => None,
8732 })
8733 .collect();
8734 if td.is_empty() {
8735 return nanmedian_numeric(values);
8743 }
8744 let n = td.len();
8747 let mid = n / 2;
8748 let (left, mid_ref, _right) = td.select_nth_unstable(mid);
8749 let mid_val = *mid_ref;
8750 let median_ns = if n.is_multiple_of(2) {
8751 let lower = left.iter().copied().fold(i64::MIN, i64::max);
8752 (i128::from(lower) + i128::from(mid_val)) / 2
8754 } else {
8755 i128::from(mid_val)
8756 };
8757 make.make(median_ns as i64)
8758}
8759
8760fn nanmedian_numeric(values: &[Scalar]) -> Scalar {
8764 let mut nums = collect_finite(values);
8765 if nums.is_empty() {
8766 return Scalar::Null(NullKind::NaN);
8767 }
8768 let n = nums.len();
8775 let mid = n / 2;
8776 let cmp = |a: &f64, b: &f64| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal);
8777 let (left, mid_ref, _right) = nums.select_nth_unstable_by(mid, cmp);
8778 let mid_val = *mid_ref;
8779 if n.is_multiple_of(2) {
8780 let lower = left.iter().copied().fold(f64::NEG_INFINITY, f64::max);
8781 Scalar::Float64((lower + mid_val) / 2.0)
8782 } else {
8783 Scalar::Float64(mid_val)
8784 }
8785}
8786
8787pub fn nanvar(values: &[Scalar], ddof: usize) -> Scalar {
8788 if let Some(td) = collect_timedelta_ns_f64(values) {
8791 if td.len() <= ddof {
8792 return Scalar::Timedelta64(Timedelta::NAT);
8793 }
8794 let mean: f64 = td.iter().sum::<f64>() / td.len() as f64;
8795 let sum_sq: f64 = td.iter().map(|x| (x - mean).powi(2)).sum();
8796 return float_ns_to_timedelta(sum_sq / (td.len() - ddof) as f64);
8797 }
8798 let nums = collect_finite(values);
8799 if nums.len() <= ddof {
8800 return Scalar::Null(NullKind::NaN);
8801 }
8802 let mean: f64 = nums.iter().sum::<f64>() / nums.len() as f64;
8803 let sum_sq: f64 = nums.iter().map(|x| (x - mean).powi(2)).sum();
8804 Scalar::Float64(sum_sq / (nums.len() - ddof) as f64)
8805}
8806
8807pub fn nanstd(values: &[Scalar], ddof: usize) -> Scalar {
8808 if let Some((td, family)) = collect_temporal_backing(values)
8827 && !matches!(family, TemporalFamily::Period(_))
8828 {
8829 if td.len() <= ddof {
8830 return Scalar::Timedelta64(Timedelta::NAT);
8831 }
8832 let mean: f64 = td.iter().sum::<f64>() / td.len() as f64;
8833 let sum_sq: f64 = td.iter().map(|x| (x - mean).powi(2)).sum();
8834 let var = sum_sq / (td.len() - ddof) as f64;
8835 return float_ns_to_timedelta(var.sqrt());
8836 }
8837 match nanvar(values, ddof) {
8838 Scalar::Float64(v) => Scalar::Float64(v.sqrt()),
8839 other => other,
8840 }
8841}
8842
8843pub fn nansem(values: &[Scalar], ddof: usize) -> Scalar {
8849 if let Some(td) = collect_timedelta_ns_f64(values) {
8851 if td.len() <= ddof {
8852 return Scalar::Timedelta64(Timedelta::NAT);
8853 }
8854 let mean: f64 = td.iter().sum::<f64>() / td.len() as f64;
8855 let sum_sq: f64 = td.iter().map(|x| (x - mean).powi(2)).sum();
8856 let var = sum_sq / (td.len() - ddof) as f64;
8857 let std = var.sqrt();
8858 return float_ns_to_timedelta(std / (td.len() as f64).sqrt());
8859 }
8860 let nums = collect_finite(values);
8861 if nums.len() <= ddof {
8862 return Scalar::Null(NullKind::NaN);
8863 }
8864 let n = nums.len();
8865 let mean = nums.iter().sum::<f64>() / n as f64;
8866 let sum_sq = nums.iter().map(|x| (x - mean).powi(2)).sum::<f64>();
8867 let var = sum_sq / (n - ddof) as f64;
8868 let std = var.sqrt();
8869 Scalar::Float64(std / (n as f64).sqrt())
8870}
8871
8872pub fn nansem_grouped(values: &[Scalar], ddof: usize) -> Scalar {
8878 if collect_timedelta_ns_f64(values).is_some() {
8879 return nansem(values, ddof);
8880 }
8881 grouped_moments(values)
8882 .sem(ddof)
8883 .map_or(Scalar::Null(NullKind::NaN), Scalar::Float64)
8884}
8885
8886#[derive(Clone, Copy, Debug, Default, PartialEq)]
8893pub struct KahanSum {
8894 sum: f64,
8895 compensation: f64,
8896}
8897
8898impl KahanSum {
8899 #[inline]
8901 pub fn add(&mut self, value: f64) {
8902 let y = value - self.compensation;
8903 let t = self.sum + y;
8904 self.compensation = t - self.sum - y;
8905 if self.compensation.is_nan() {
8906 self.compensation = 0.0;
8907 }
8908 self.sum = t;
8909 }
8910
8911 #[inline]
8913 #[must_use]
8914 pub fn sum(self) -> f64 {
8915 self.sum
8916 }
8917}
8918
8919#[derive(Clone, Copy, Debug, Default, PartialEq)]
8926pub struct WelfordVar {
8927 count: usize,
8928 mean: f64,
8929 m2: f64,
8930}
8931
8932impl WelfordVar {
8933 #[inline]
8935 pub fn add(&mut self, value: f64) {
8936 self.count += 1;
8937 let old = self.mean;
8938 self.mean += (value - old) / self.count as f64;
8939 self.m2 += (value - self.mean) * (value - old);
8940 }
8941
8942 #[must_use]
8944 pub fn count(self) -> usize {
8945 self.count
8946 }
8947
8948 #[must_use]
8950 pub fn var(self, ddof: usize) -> Option<f64> {
8951 (self.count > ddof).then(|| self.m2 / (self.count - ddof) as f64)
8952 }
8953
8954 #[must_use]
8956 pub fn std(self, ddof: usize) -> Option<f64> {
8957 self.var(ddof).map(f64::sqrt)
8958 }
8959
8960 #[must_use]
8962 pub fn sem(self, ddof: usize) -> Option<f64> {
8963 self.var(ddof).map(|var| (var / self.count as f64).sqrt())
8964 }
8965}
8966
8967#[derive(Clone, Copy, Debug, Default, PartialEq)]
8975pub struct SkewMoments {
8976 count: usize,
8977 m1: f64,
8978 m2: f64,
8979 m3: f64,
8980}
8981
8982impl SkewMoments {
8983 #[inline]
8985 pub fn add(&mut self, value: f64) {
8986 let before = self.count as f64;
8987 self.count += 1;
8988 let n = self.count as f64;
8989 let delta = value - self.m1;
8990 let delta_n = delta / n;
8991 let term1 = delta * delta_n * before;
8992 self.m1 += delta_n;
8993 self.m3 += term1 * delta_n * (n - 2.0) - 3.0 * delta_n * self.m2;
8994 self.m2 += term1;
8995 }
8996
8997 #[must_use]
8999 pub fn count(self) -> usize {
9000 self.count
9001 }
9002
9003 #[must_use]
9005 pub fn skew(self) -> Option<f64> {
9006 if self.count < 3 {
9007 return None;
9008 }
9009 if self.m2 == 0.0 {
9010 return Some(0.0);
9011 }
9012 let n = self.count as f64;
9013 let half = std::hint::black_box(0.5);
9017 Some((n * (n - 1.0).powf(half) / (n - 2.0)) * (self.m3 / self.m2.powf(1.5)))
9018 }
9019}
9020
9021#[must_use]
9024pub fn nanskew_grouped(values: &[Scalar]) -> Scalar {
9025 let mut moments = SkewMoments::default();
9026 for value in values {
9027 if value.is_missing() {
9028 continue;
9029 }
9030 if let Ok(x) = value.to_f64() {
9031 moments.add(x);
9032 }
9033 }
9034 moments
9035 .skew()
9036 .map_or(Scalar::Null(NullKind::NaN), Scalar::Float64)
9037}
9038
9039fn grouped_moments(values: &[Scalar]) -> WelfordVar {
9041 let mut moments = WelfordVar::default();
9042 for value in values {
9043 if value.is_missing() {
9044 continue;
9045 }
9046 if let Ok(x) = value.to_f64() {
9047 moments.add(x);
9048 }
9049 }
9050 moments
9051}
9052
9053#[must_use]
9057pub fn nansum_grouped(values: &[Scalar]) -> Scalar {
9058 if collect_timedelta_ns(values).is_some() {
9059 return nansum(values);
9060 }
9061 let mut sum = KahanSum::default();
9062 for value in values {
9063 if value.is_missing() {
9064 continue;
9065 }
9066 if let Ok(x) = value.to_f64() {
9067 sum.add(x);
9068 }
9069 }
9070 Scalar::Float64(sum.sum())
9071}
9072
9073#[must_use]
9076pub fn nanmean_grouped(values: &[Scalar]) -> Scalar {
9077 if collect_timedelta_ns(values).is_some() || collect_datetime_ns(values).is_some() {
9078 return nanmean(values);
9079 }
9080 let mut sum = KahanSum::default();
9081 let mut count = 0_usize;
9082 for value in values {
9083 if value.is_missing() {
9084 continue;
9085 }
9086 if let Ok(x) = value.to_f64() {
9087 sum.add(x);
9088 count += 1;
9089 }
9090 }
9091 if count == 0 {
9092 return Scalar::Null(NullKind::NaN);
9093 }
9094 Scalar::Float64(sum.sum() / count as f64)
9095}
9096
9097#[must_use]
9100pub fn nanvar_grouped(values: &[Scalar], ddof: usize) -> Scalar {
9101 if collect_timedelta_ns_f64(values).is_some() {
9102 return nanvar(values, ddof);
9103 }
9104 grouped_moments(values)
9105 .var(ddof)
9106 .map_or(Scalar::Null(NullKind::NaN), Scalar::Float64)
9107}
9108
9109#[must_use]
9112pub fn nanstd_grouped(values: &[Scalar], ddof: usize) -> Scalar {
9113 if collect_temporal_backing(values).is_some() {
9114 return nanstd(values, ddof);
9115 }
9116 grouped_moments(values)
9117 .std(ddof)
9118 .map_or(Scalar::Null(NullKind::NaN), Scalar::Float64)
9119}
9120
9121pub fn nanptp(values: &[Scalar]) -> Scalar {
9126 if is_datetime_input(values) {
9134 let (mut lo, mut hi) = (i64::MAX, i64::MIN);
9135 for value in values {
9136 if value.is_missing() {
9137 continue;
9138 }
9139 if let Scalar::Datetime64(ns) = value {
9140 lo = lo.min(*ns);
9141 hi = hi.max(*ns);
9142 }
9143 }
9144 return timedelta_ns_to_scalar(i128::from(hi) - i128::from(lo));
9145 }
9146 let (mut td_lo, mut td_hi) = (i64::MAX, i64::MIN);
9150 let mut saw_timedelta = false;
9151 let mut all_timedelta = true;
9152 for value in values {
9153 if value.is_missing() {
9154 continue;
9155 }
9156 match value {
9157 Scalar::Timedelta64(ns) => {
9158 saw_timedelta = true;
9159 td_lo = td_lo.min(*ns);
9160 td_hi = td_hi.max(*ns);
9161 }
9162 _ => {
9163 all_timedelta = false;
9164 break;
9165 }
9166 }
9167 }
9168 if all_timedelta && saw_timedelta {
9169 return timedelta_ns_to_scalar(i128::from(td_hi) - i128::from(td_lo));
9173 }
9174 let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY);
9179 let mut seen = false;
9180 for v in values {
9181 if v.is_missing() {
9182 continue;
9183 }
9184 if let Ok(x) = v.to_f64() {
9185 seen = true;
9186 if x < lo {
9187 lo = x;
9188 }
9189 if x > hi {
9190 hi = x;
9191 }
9192 }
9193 }
9194 if !seen {
9195 return Scalar::Null(NullKind::NaN);
9196 }
9197 Scalar::Float64(hi - lo)
9198}
9199
9200pub fn nanskew(values: &[Scalar]) -> Scalar {
9206 let nums = collect_finite(values);
9207 let n = nums.len() as f64;
9208 if n < 3.0 {
9209 return Scalar::Null(NullKind::NaN);
9210 }
9211 let mean = nums.iter().sum::<f64>() / n;
9212 let (mut m2, mut m3) = (0.0_f64, 0.0_f64);
9216 for x in nums {
9217 let delta = x - mean;
9218 let d2 = delta * delta;
9224 m2 += d2;
9225 m3 += d2 * delta;
9226 }
9227 let s2 = m2 / (n - 1.0);
9228 if s2 == 0.0 {
9229 return Scalar::Float64(0.0);
9230 }
9231 let s3 = s2.powf(1.5);
9232 Scalar::Float64((n / ((n - 1.0) * (n - 2.0))) * (m3 / s3))
9233}
9234
9235pub fn nankurt(values: &[Scalar]) -> Scalar {
9242 let nums = collect_finite(values);
9243 let n = nums.len() as f64;
9244 if n < 4.0 {
9245 return Scalar::Null(NullKind::NaN);
9246 }
9247 let mean = nums.iter().sum::<f64>() / n;
9248 let (mut m2, mut m4) = (0.0_f64, 0.0_f64);
9252 for x in nums {
9253 let delta = x - mean;
9254 let d2 = delta * delta;
9257 m2 += d2;
9258 m4 += d2 * d2;
9259 }
9260 let s2 = m2 / (n - 1.0);
9261 if s2 == 0.0 {
9262 return Scalar::Float64(0.0);
9263 }
9264 let adj = (n * (n + 1.0)) / ((n - 1.0) * (n - 2.0) * (n - 3.0));
9265 let sub = (3.0 * (n - 1.0).powi(2)) / ((n - 2.0) * (n - 3.0));
9266 Scalar::Float64(adj * (m4 / (s2 * s2)) - sub)
9267}
9268
9269pub fn nanprod(values: &[Scalar]) -> Scalar {
9271 if is_timedelta_input(values) {
9278 return Scalar::Null(NullKind::NaN);
9279 }
9280 let mut prod = 1.0_f64;
9285 for v in values {
9286 if v.is_missing() {
9287 continue;
9288 }
9289 if let Ok(x) = v.to_f64() {
9290 prod *= x;
9291 }
9292 }
9293 Scalar::Float64(prod)
9294}
9295
9296fn is_timedelta_input(values: &[Scalar]) -> bool {
9302 let mut saw_td = false;
9303 for v in values {
9304 if v.is_missing() {
9305 continue;
9306 }
9307 match v {
9308 Scalar::Timedelta64(_) => saw_td = true,
9309 _ => return false,
9310 }
9311 }
9312 saw_td
9313}
9314
9315fn collect_datetime_ns(values: &[Scalar]) -> Option<(i128, usize)> {
9325 let mut sum: i128 = 0;
9326 let mut count: usize = 0;
9327 let mut saw_datetime = false;
9328 for v in values {
9329 match v {
9330 Scalar::Datetime64(ns) => {
9331 saw_datetime = true;
9332 if v.is_missing() {
9333 continue;
9334 }
9335 sum += i128::from(*ns);
9336 count += 1;
9337 }
9338 _ if v.is_missing() => continue,
9339 _ => return None,
9340 }
9341 }
9342 if saw_datetime {
9343 Some((sum, count))
9344 } else {
9345 None
9346 }
9347}
9348
9349fn is_datetime_input(values: &[Scalar]) -> bool {
9356 let mut saw_dt = false;
9357 for v in values {
9358 if v.is_missing() {
9359 continue;
9360 }
9361 match v {
9362 Scalar::Datetime64(_) => saw_dt = true,
9363 _ => return false,
9364 }
9365 }
9366 saw_dt
9367}
9368
9369fn is_int64_input(values: &[Scalar]) -> bool {
9371 let mut saw_int = false;
9372 for value in values {
9373 if value.is_missing() {
9374 continue;
9375 }
9376 match value {
9377 Scalar::Int64(_) => saw_int = true,
9378 _ => return false,
9379 }
9380 }
9381 saw_int
9382}
9383
9384fn is_interval_input(values: &[Scalar]) -> bool {
9387 let mut saw_interval = false;
9388 for v in values {
9389 if v.is_missing() {
9390 continue;
9391 }
9392 match v {
9393 Scalar::Interval(_) => saw_interval = true,
9394 _ => return false,
9395 }
9396 }
9397 saw_interval
9398}
9399
9400fn nanarg_interval(values: &[Scalar], find_max: bool) -> Option<usize> {
9412 let mut best: Option<(usize, (f64, f64))> = None;
9413 for (index, value) in values.iter().enumerate() {
9414 if value.is_missing() {
9415 continue;
9416 }
9417 let Scalar::Interval(iv) = value else {
9418 continue;
9419 };
9420 if iv.left.is_nan() || iv.right.is_nan() {
9421 return None;
9422 }
9423 let key = (iv.left, iv.right);
9424 match best {
9425 None => best = Some((index, key)),
9426 Some((_, current)) if (find_max && key > current) || (!find_max && key < current) => {
9429 best = Some((index, key));
9430 }
9431 _ => {}
9432 }
9433 }
9434 best.map(|(index, _)| index)
9435}
9436
9437fn nanarg_i64(values: &[Scalar], find_max: bool) -> Option<usize> {
9438 let mut best: Option<(usize, i64)> = None;
9439 for (index, value) in values.iter().enumerate() {
9440 if value.is_missing() {
9441 continue;
9442 }
9443 let candidate = match value {
9452 Scalar::Int64(raw) | Scalar::Timedelta64(raw) | Scalar::Datetime64(raw) => raw,
9453 Scalar::Period(p) => &p.ordinal,
9454 _ => continue,
9455 };
9456 match best {
9457 None => best = Some((index, *candidate)),
9458 Some((_, current))
9459 if (find_max && *candidate > current) || (!find_max && *candidate < current) =>
9460 {
9461 best = Some((index, *candidate));
9462 }
9463 _ => {}
9464 }
9465 }
9466 best.map(|(index, _)| index)
9467}
9468
9469fn timedelta_cumulative<F>(values: &[Scalar], init: i128, mut step: F) -> Vec<Scalar>
9474where
9475 F: FnMut(i128, i128) -> i128,
9476{
9477 let mut out = Vec::with_capacity(values.len());
9478 let mut running: i128 = init;
9479 for v in values {
9480 if v.is_missing() {
9481 out.push(Scalar::Null(NullKind::NaT));
9482 continue;
9483 }
9484 if let Scalar::Timedelta64(ns) = v {
9485 running = step(running, i128::from(*ns));
9492 out.push(timedelta_ns_to_scalar(running));
9493 } else {
9494 out.push(Scalar::Null(NullKind::NaT));
9495 }
9496 }
9497 out
9498}
9499
9500fn timedelta_cumulative_extrema<F>(
9508 values: &[Scalar],
9509 sentinel: i64,
9510 make: TemporalFamily,
9511 mut step: F,
9512) -> Vec<Scalar>
9513where
9514 F: FnMut(i64, i64) -> i64,
9515{
9516 let mut out = Vec::with_capacity(values.len());
9517 let mut running: Option<i64> = None;
9518 for v in values {
9519 if v.is_missing() {
9520 out.push(Scalar::Null(NullKind::NaT));
9521 continue;
9522 }
9523 let raw = match v {
9525 Scalar::Timedelta64(ns) | Scalar::Datetime64(ns) => Some(*ns),
9526 Scalar::Period(p) => Some(p.ordinal),
9527 _ => None,
9528 };
9529 if let Some(ns) = raw.as_ref() {
9530 let new_val = match running {
9531 Some(prev) => step(prev, *ns),
9532 None => *ns,
9533 };
9534 running = Some(new_val);
9535 out.push(make.make(new_val));
9536 } else {
9537 out.push(Scalar::Null(NullKind::NaT));
9538 }
9539 }
9540 let _ = sentinel; out
9542}
9543
9544#[must_use]
9565pub fn nancumsum_with_policy(values: &[Scalar], policy: OverflowPolicy) -> Vec<Scalar> {
9566 if !matches!(policy, OverflowPolicy::Strict) || !is_timedelta_input(values) {
9567 return nancumsum(values);
9568 }
9569 let mut out = Vec::with_capacity(values.len());
9570 let mut running: i64 = 0;
9571 for value in values {
9572 if value.is_missing() {
9573 out.push(Scalar::Null(NullKind::NaT));
9574 continue;
9575 }
9576 if let Scalar::Timedelta64(ns) = value {
9577 running = running.wrapping_add(*ns);
9580 out.push(Scalar::Timedelta64(running));
9581 } else {
9582 out.push(Scalar::Null(NullKind::NaT));
9583 }
9584 }
9585 out
9586}
9587
9588pub fn nancumsum(values: &[Scalar]) -> Vec<Scalar> {
9589 if is_timedelta_input(values) {
9593 return timedelta_cumulative(values, 0_i128, |acc, x| acc.saturating_add(x));
9594 }
9595 let mut out = Vec::with_capacity(values.len());
9596 let mut running = 0.0_f64;
9597 for v in values {
9598 if v.is_missing() {
9599 out.push(Scalar::Null(NullKind::NaN));
9600 continue;
9601 }
9602 match v.to_f64() {
9603 Ok(x) if !x.is_nan() => {
9604 running += x;
9605 out.push(Scalar::Float64(running));
9606 }
9607 _ => out.push(Scalar::Null(NullKind::NaN)),
9608 }
9609 }
9610 out
9611}
9612
9613pub fn nancumprod(values: &[Scalar]) -> Vec<Scalar> {
9618 let mut out = Vec::with_capacity(values.len());
9619 let mut running = 1.0_f64;
9620 for v in values {
9621 if v.is_missing() {
9622 out.push(Scalar::Null(NullKind::NaN));
9623 continue;
9624 }
9625 match v.to_f64() {
9626 Ok(x) if !x.is_nan() => {
9627 running *= x;
9628 out.push(Scalar::Float64(running));
9629 }
9630 _ => out.push(Scalar::Null(NullKind::NaN)),
9631 }
9632 }
9633 out
9634}
9635
9636pub fn nancummax(values: &[Scalar]) -> Vec<Scalar> {
9642 if let Some((_, family)) = collect_temporal_backing(values) {
9648 return timedelta_cumulative_extrema(values, i64::MAX, family, |acc, x| acc.max(x));
9649 }
9650 let mut out = Vec::with_capacity(values.len());
9651 let mut running: Option<f64> = None;
9652 for v in values {
9653 if v.is_missing() {
9654 out.push(Scalar::Null(NullKind::NaN));
9655 continue;
9656 }
9657 match v.to_f64() {
9658 Ok(x) if !x.is_nan() => {
9659 let new_val = match running {
9660 Some(prev) => prev.max(x),
9661 None => x,
9662 };
9663 running = Some(new_val);
9664 out.push(Scalar::Float64(new_val));
9665 }
9666 _ => out.push(Scalar::Null(NullKind::NaN)),
9667 }
9668 }
9669 out
9670}
9671
9672pub fn nancummin(values: &[Scalar]) -> Vec<Scalar> {
9676 if is_timedelta_input(values) {
9678 return timedelta_cumulative_extrema(
9679 values,
9680 i64::MIN,
9681 TemporalFamily::Timedelta,
9682 |acc, x| acc.min(x),
9683 );
9684 }
9685 if let Some((_, family)) = collect_temporal_backing(values) {
9687 return timedelta_cumulative_extrema(values, i64::MIN, family, |acc, x| acc.min(x));
9688 }
9689 let mut out = Vec::with_capacity(values.len());
9690 let mut running: Option<f64> = None;
9691 for v in values {
9692 if v.is_missing() {
9693 out.push(Scalar::Null(NullKind::NaN));
9694 continue;
9695 }
9696 match v.to_f64() {
9697 Ok(x) if !x.is_nan() => {
9698 let new_val = match running {
9699 Some(prev) => prev.min(x),
9700 None => x,
9701 };
9702 running = Some(new_val);
9703 out.push(Scalar::Float64(new_val));
9704 }
9705 _ => out.push(Scalar::Null(NullKind::NaN)),
9706 }
9707 }
9708 out
9709}
9710
9711pub fn nanquantile(values: &[Scalar], q: f64) -> Scalar {
9717 if !(0.0..=1.0).contains(&q) {
9718 return Scalar::Null(NullKind::NaN);
9719 }
9720 if let Some((mut td, make)) = collect_temporal_backing(values) {
9723 if td.is_empty() {
9724 return make.nat();
9725 }
9726 let n = td.len();
9727 if n == 1 {
9728 return float_ns_to_temporal(td[0], make);
9729 }
9730 let pos = q * (n - 1) as f64;
9731 let lo = pos.floor() as usize;
9732 let hi = pos.ceil() as usize;
9733 let cmp = |a: &f64, b: &f64| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal);
9737 let (_left, lo_ref, right) = td.select_nth_unstable_by(lo, cmp);
9738 let lo_val = *lo_ref;
9739 let ns = if lo == hi {
9740 lo_val
9741 } else {
9742 let hi_val = right.iter().copied().fold(f64::INFINITY, f64::min);
9743 let weight = pos - lo as f64;
9744 lo_val + (hi_val - lo_val) * weight
9745 };
9746 return float_ns_to_temporal(ns, make);
9747 }
9748 let mut nums = collect_finite(values);
9749 if nums.is_empty() {
9750 return Scalar::Null(NullKind::NaN);
9751 }
9752 let n = nums.len();
9753 if n == 1 {
9754 return Scalar::Float64(nums[0]);
9755 }
9756 let pos = q * (n - 1) as f64;
9757 let lo = pos.floor() as usize;
9758 let hi = pos.ceil() as usize;
9759 let cmp = |a: &f64, b: &f64| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal);
9764 let (_left, lo_ref, right) = nums.select_nth_unstable_by(lo, cmp);
9765 let lo_val = *lo_ref;
9766 if lo == hi {
9767 return Scalar::Float64(lo_val);
9768 }
9769 let hi_val = right.iter().copied().fold(f64::INFINITY, f64::min);
9770 let weight = pos - lo as f64;
9771 Scalar::Float64(lo_val + (hi_val - lo_val) * weight)
9772}
9773
9774pub fn nanargmax(values: &[Scalar]) -> Option<usize> {
9779 if is_int64_input(values) || collect_temporal_backing(values).is_some() {
9784 return nanarg_i64(values, true);
9785 }
9786 if is_interval_input(values) {
9790 return nanarg_interval(values, true);
9791 }
9792 let mut best: Option<(usize, f64)> = None;
9793 for (i, v) in values.iter().enumerate() {
9794 if v.is_missing() {
9795 continue;
9796 }
9797 if let Ok(x) = v.to_f64() {
9798 if x.is_nan() {
9799 continue;
9800 }
9801 match best {
9802 None => best = Some((i, x)),
9803 Some((_, cur)) if x > cur => best = Some((i, x)),
9804 _ => {}
9805 }
9806 }
9807 }
9808 best.map(|(i, _)| i)
9809}
9810
9811pub fn nanargmin(values: &[Scalar]) -> Option<usize> {
9815 if is_int64_input(values) || collect_temporal_backing(values).is_some() {
9818 return nanarg_i64(values, false);
9819 }
9820 if is_interval_input(values) {
9822 return nanarg_interval(values, false);
9823 }
9824 let mut best: Option<(usize, f64)> = None;
9825 for (i, v) in values.iter().enumerate() {
9826 if v.is_missing() {
9827 continue;
9828 }
9829 if let Ok(x) = v.to_f64() {
9830 if x.is_nan() {
9831 continue;
9832 }
9833 match best {
9834 None => best = Some((i, x)),
9835 Some((_, cur)) if x < cur => best = Some((i, x)),
9836 _ => {}
9837 }
9838 }
9839 }
9840 best.map(|(i, _)| i)
9841}
9842
9843pub fn nannunique(values: &[Scalar]) -> Scalar {
9845 use rustc_hash::FxHashSet;
9846 #[derive(Hash, PartialEq, Eq)]
9847 enum ScalarKey<'a> {
9848 Bool(bool),
9849 Int64(i64),
9850 FloatBits(u64),
9851 Utf8(&'a str),
9852 Timedelta64(i64),
9853 Datetime64(i64),
9854 Period(i64, PeriodFreq),
9855 Interval(u64, u64, IntervalClosed),
9856 Object(String),
9859 }
9860
9861 let mut seen = FxHashSet::default();
9862 for val in values {
9863 if val.is_missing() {
9864 continue;
9865 }
9866 let key = match val {
9867 Scalar::Bool(v) => ScalarKey::Bool(*v),
9868 Scalar::Int64(v) => ScalarKey::Int64(*v),
9869 Scalar::Float64(v) => {
9870 let normalized = if *v == 0.0 { 0.0 } else { *v };
9871 ScalarKey::FloatBits(normalized.to_bits())
9872 }
9873 Scalar::Utf8(v) => ScalarKey::Utf8(v.as_str()),
9874 Scalar::Timedelta64(v) => ScalarKey::Timedelta64(*v),
9875 Scalar::Datetime64(v) => ScalarKey::Datetime64(*v),
9876 Scalar::Period(p) => ScalarKey::Period(p.ordinal, p.freq),
9877 Scalar::Interval(v) => ScalarKey::Interval(
9878 normalized_float_bits(v.left),
9879 normalized_float_bits(v.right),
9880 v.closed,
9881 ),
9882 Scalar::Object(object) => ScalarKey::Object(object.repr()),
9883 Scalar::Null(_) => continue,
9884 };
9885 seen.insert(key);
9886 }
9887 Scalar::Int64(seen.len() as i64)
9888}
9889
9890fn normalized_float_bits(value: f64) -> u64 {
9891 let normalized = if value == 0.0 { 0.0 } else { value };
9892 normalized.to_bits()
9893}
9894
9895#[derive(
9915 Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize,
9916)]
9917#[serde(rename_all = "snake_case")]
9918#[non_exhaustive]
9919pub enum IntervalClosed {
9920 Left,
9922 #[default]
9924 Right,
9925 Both,
9927 Neither,
9929}
9930
9931impl IntervalClosed {
9932 #[must_use]
9934 pub fn left_closed(self) -> bool {
9935 matches!(self, Self::Left | Self::Both)
9936 }
9937
9938 #[must_use]
9940 pub fn right_closed(self) -> bool {
9941 matches!(self, Self::Right | Self::Both)
9942 }
9943}
9944
9945impl std::fmt::Display for IntervalClosed {
9946 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
9947 match self {
9948 Self::Left => write!(f, "left"),
9949 Self::Right => write!(f, "right"),
9950 Self::Both => write!(f, "both"),
9951 Self::Neither => write!(f, "neither"),
9952 }
9953 }
9954}
9955
9956#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
9961#[serde(rename_all = "snake_case")]
9962pub enum IntervalSubtype {
9963 #[default]
9964 Float64,
9965 Int64,
9966}
9967
9968impl IntervalSubtype {
9969 #[must_use]
9971 pub const fn is_float(&self) -> bool {
9972 matches!(self, Self::Float64)
9973 }
9974
9975 #[must_use]
9977 pub const fn name(&self) -> &'static str {
9978 match self {
9979 Self::Float64 => "float64",
9980 Self::Int64 => "int64",
9981 }
9982 }
9983}
9984
9985#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
9992pub struct Interval {
9993 pub left: f64,
9994 pub right: f64,
9995 #[serde(default)]
9996 pub closed: IntervalClosed,
9997 #[serde(default, skip_serializing_if = "IntervalSubtype::is_float")]
9999 pub subtype: IntervalSubtype,
10000}
10001
10002impl PartialEq for Interval {
10003 fn eq(&self, other: &Self) -> bool {
10004 self.left == other.left && self.right == other.right && self.closed == other.closed
10005 }
10006}
10007
10008impl Eq for Interval {}
10012
10013impl Interval {
10014 fn endpoint_key(value: f64) -> f64 {
10016 if value == 0.0 { 0.0 } else { value }
10017 }
10018}
10019
10020impl std::hash::Hash for Interval {
10023 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
10024 Self::endpoint_key(self.left).to_bits().hash(state);
10025 Self::endpoint_key(self.right).to_bits().hash(state);
10026 self.closed.hash(state);
10027 }
10028}
10029
10030impl Ord for Interval {
10033 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
10034 Self::endpoint_key(self.left)
10035 .total_cmp(&Self::endpoint_key(other.left))
10036 .then_with(|| {
10037 Self::endpoint_key(self.right).total_cmp(&Self::endpoint_key(other.right))
10038 })
10039 .then_with(|| self.closed.cmp(&other.closed))
10040 }
10041}
10042
10043impl PartialOrd for Interval {
10044 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
10045 Some(self.cmp(other))
10046 }
10047}
10048
10049impl Interval {
10050 #[must_use]
10053 pub const fn new(left: f64, right: f64, closed: IntervalClosed) -> Self {
10054 Self {
10055 left,
10056 right,
10057 closed,
10058 subtype: IntervalSubtype::Float64,
10059 }
10060 }
10061
10062 #[must_use]
10065 pub fn with_int_endpoints(self) -> Self {
10066 if self.left.fract() == 0.0 && self.right.fract() == 0.0 {
10067 Self {
10068 subtype: IntervalSubtype::Int64,
10069 ..self
10070 }
10071 } else {
10072 self
10073 }
10074 }
10075
10076 #[must_use]
10078 pub fn length(&self) -> f64 {
10079 self.right - self.left
10080 }
10081
10082 #[must_use]
10084 pub fn mid(&self) -> f64 {
10085 (self.left + self.right) / 2.0
10086 }
10087
10088 #[must_use]
10091 pub fn is_empty(&self) -> bool {
10092 self.left == self.right && !matches!(self.closed, IntervalClosed::Both)
10093 }
10094
10095 #[must_use]
10100 pub fn contains(&self, value: f64) -> bool {
10101 if value.is_nan() {
10102 return false;
10103 }
10104 let left_ok = if self.closed.left_closed() {
10105 value >= self.left
10106 } else {
10107 value > self.left
10108 };
10109 let right_ok = if self.closed.right_closed() {
10110 value <= self.right
10111 } else {
10112 value < self.right
10113 };
10114 left_ok && right_ok
10115 }
10116
10117 #[must_use]
10124 pub fn overlaps(&self, other: &Self) -> bool {
10125 if self.left > other.right || other.left > self.right {
10126 return false;
10127 }
10128 if self.right == other.left {
10130 return self.closed.right_closed() && other.closed.left_closed();
10131 }
10132 if other.right == self.left {
10133 return other.closed.right_closed() && self.closed.left_closed();
10134 }
10135 true
10136 }
10137
10138 pub fn parse(s: &str) -> Result<Self, TypeError> {
10144 let s = s.trim();
10145 if s.len() < 5 {
10146 return Err(TypeError::ValueNotParseable {
10147 value: s.to_string(),
10148 target: "Interval".to_string(),
10149 });
10150 }
10151
10152 let first_char = s.chars().next().unwrap();
10153 let last_char = s.chars().last().unwrap();
10154
10155 let left_closed = match first_char {
10156 '[' => true,
10157 '(' => false,
10158 _ => {
10159 return Err(TypeError::ValueNotParseable {
10160 value: s.to_string(),
10161 target: "Interval".to_string(),
10162 });
10163 }
10164 };
10165
10166 let right_closed = match last_char {
10167 ']' => true,
10168 ')' => false,
10169 _ => {
10170 return Err(TypeError::ValueNotParseable {
10171 value: s.to_string(),
10172 target: "Interval".to_string(),
10173 });
10174 }
10175 };
10176
10177 let closed = match (left_closed, right_closed) {
10178 (true, true) => IntervalClosed::Both,
10179 (true, false) => IntervalClosed::Left,
10180 (false, true) => IntervalClosed::Right,
10181 (false, false) => IntervalClosed::Neither,
10182 };
10183
10184 let inner = &s[1..s.len() - 1];
10185 let Some((left_text, right_text)) = inner.split_once(',') else {
10186 return Err(TypeError::ValueNotParseable {
10187 value: s.to_string(),
10188 target: "Interval".to_string(),
10189 });
10190 };
10191 if right_text.contains(',') {
10192 return Err(TypeError::ValueNotParseable {
10193 value: s.to_string(),
10194 target: "Interval".to_string(),
10195 });
10196 }
10197
10198 let left: f64 = left_text
10199 .trim()
10200 .parse()
10201 .map_err(|_| TypeError::ValueNotParseable {
10202 value: s.to_string(),
10203 target: "Interval".to_string(),
10204 })?;
10205
10206 let right: f64 = right_text
10207 .trim()
10208 .parse()
10209 .map_err(|_| TypeError::ValueNotParseable {
10210 value: s.to_string(),
10211 target: "Interval".to_string(),
10212 })?;
10213
10214 Ok(Self::new(left, right, closed))
10215 }
10216}
10217
10218impl std::fmt::Display for Interval {
10219 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
10226 let left_bracket = if self.closed.left_closed() { '[' } else { '(' };
10227 let right_bracket = if self.closed.right_closed() { ']' } else { ')' };
10228 #[allow(clippy::cast_possible_truncation)] let endpoint = |value: f64| match self.subtype {
10231 IntervalSubtype::Int64 if value.fract() == 0.0 => format!("{}", value as i64),
10232 _ => float_to_string_for_astype(value),
10233 };
10234 write!(
10235 f,
10236 "{left_bracket}{}, {}{right_bracket}",
10237 endpoint(self.left),
10238 endpoint(self.right)
10239 )
10240 }
10241}
10242
10243#[must_use]
10261pub fn interval_range_by_periods(
10262 start: f64,
10263 end: f64,
10264 periods: usize,
10265 closed: IntervalClosed,
10266) -> Vec<Interval> {
10267 if periods == 0 || !start.is_finite() || !end.is_finite() || start >= end {
10268 return Vec::new();
10269 }
10270 let step = (end - start) / (periods as f64);
10271 let mut out = Vec::with_capacity(periods);
10272 for i in 0..periods {
10273 let left = start + step * (i as f64);
10274 let right = if i + 1 == periods {
10276 end
10277 } else {
10278 start + step * ((i + 1) as f64)
10279 };
10280 out.push(Interval::new(left, right, closed));
10281 }
10282 out
10283}
10284
10285pub fn interval_range_by_step(
10296 start: f64,
10297 end: f64,
10298 step: f64,
10299 closed: IntervalClosed,
10300) -> Result<Vec<Interval>, TypeError> {
10301 if !step.is_finite() || !step.is_sign_positive() || step == 0.0 {
10302 return Err(TypeError::InvalidIntervalStep { step });
10303 }
10304 if !start.is_finite() || !end.is_finite() || start >= end {
10305 return Ok(Vec::new());
10306 }
10307 let span = end - start;
10308 let periods_f = span / step;
10309 let periods = periods_f.round() as i64;
10310 if periods <= 0 {
10311 return Ok(Vec::new());
10312 }
10313 let reconstructed = step * (periods as f64);
10314 if (span - reconstructed).abs() > span.abs() * 1e-9 + 1e-12 {
10316 return Err(TypeError::IntervalStepDoesNotDivide { step, span });
10317 }
10318 let periods = periods as usize;
10319 let mut out = Vec::with_capacity(periods);
10320 for i in 0..periods {
10321 let left = start + step * (i as f64);
10322 let right = if i + 1 == periods {
10323 end
10324 } else {
10325 start + step * ((i + 1) as f64)
10326 };
10327 out.push(Interval::new(left, right, closed));
10328 }
10329 Ok(out)
10330}
10331
10332pub fn interval_range(
10344 start: Option<f64>,
10345 end: Option<f64>,
10346 periods: Option<usize>,
10347 freq: Option<f64>,
10348 closed: Option<IntervalClosed>,
10349) -> Result<Vec<Interval>, TypeError> {
10350 let count = usize::from(start.is_some())
10351 + usize::from(end.is_some())
10352 + usize::from(periods.is_some())
10353 + usize::from(freq.is_some());
10354 if count != 3 {
10355 return Err(TypeError::IntervalRangeParameterCount);
10356 }
10357 let closed = closed.unwrap_or(IntervalClosed::Right);
10358
10359 match (start, end, periods, freq) {
10360 (Some(start), Some(end), Some(periods), None) => {
10361 Ok(interval_range_by_periods(start, end, periods, closed))
10362 }
10363 (Some(start), Some(end), None, Some(freq)) => {
10364 interval_range_by_step(start, end, freq, closed)
10365 }
10366 (Some(start), None, Some(periods), Some(freq)) => {
10367 if !freq.is_finite() || !freq.is_sign_positive() || freq == 0.0 {
10368 return Err(TypeError::InvalidIntervalStep { step: freq });
10369 }
10370 if !start.is_finite() || periods == 0 {
10371 return Ok(Vec::new());
10372 }
10373 let mut out = Vec::with_capacity(periods);
10374 for i in 0..periods {
10375 let left = start + freq * (i as f64);
10376 let right = start + freq * ((i + 1) as f64);
10377 out.push(Interval::new(left, right, closed));
10378 }
10379 Ok(out)
10380 }
10381 (None, Some(end), Some(periods), Some(freq)) => {
10382 if !freq.is_finite() || !freq.is_sign_positive() || freq == 0.0 {
10383 return Err(TypeError::InvalidIntervalStep { step: freq });
10384 }
10385 if !end.is_finite() || periods == 0 {
10386 return Ok(Vec::new());
10387 }
10388 let start = end - freq * (periods as f64);
10389 let mut out = Vec::with_capacity(periods);
10390 for i in 0..periods {
10391 let left = start + freq * (i as f64);
10392 let right = if i + 1 == periods {
10393 end
10394 } else {
10395 start + freq * ((i + 1) as f64)
10396 };
10397 out.push(Interval::new(left, right, closed));
10398 }
10399 Ok(out)
10400 }
10401 _ => Err(TypeError::IntervalRangeParameterCount),
10402 }
10403}
10404
10405#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
10424#[serde(rename_all = "SCREAMING-KEBAB-CASE")]
10425#[non_exhaustive]
10426pub enum PeriodFreq {
10427 Annual(u8),
10431 Quarterly(u8),
10435 Monthly,
10437 Weekly(u8),
10440 Daily,
10442 Business,
10444 Hourly,
10446 Minutely,
10448 Secondly,
10450 Milliseconds,
10452 Microseconds,
10454 Nanoseconds,
10456}
10457
10458const PERIOD_MONTHS: [&str; 12] = [
10460 "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC",
10461];
10462const PERIOD_WEEKDAYS: [&str; 7] = ["MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"];
10464
10465impl PeriodFreq {
10466 pub const ANNUAL: Self = Self::Annual(12);
10468 pub const QUARTERLY: Self = Self::Quarterly(12);
10470 pub const WEEKLY: Self = Self::Weekly(6);
10472
10473 #[must_use]
10479 pub const fn fiscal_month_shift(self) -> i64 {
10480 match self {
10481 Self::Annual(month) | Self::Quarterly(month) => (12 - (month as i64 % 12)) % 12,
10482 _ => 0,
10483 }
10484 }
10485
10486 #[must_use]
10491 pub const fn week_start_shift(self) -> i64 {
10492 match self {
10493 Self::Weekly(day) => (day as i64 % 7 + 1) % 7,
10494 _ => 0,
10495 }
10496 }
10497
10498 fn parse_anchored(alias: &str) -> Option<Self> {
10501 let (prefix, anchor) = alias.split_once('-')?;
10502 let month = PERIOD_MONTHS.iter().position(|name| *name == anchor);
10503 let day = PERIOD_WEEKDAYS.iter().position(|name| *name == anchor);
10504 match (prefix, month, day) {
10505 ("A" | "Y", Some(month), _) => Some(Self::Annual(month as u8 + 1)),
10506 ("Q", Some(month), _) => Some(Self::Quarterly(month as u8 + 1)),
10507 ("W", _, Some(day)) => Some(Self::Weekly(day as u8)),
10508 _ => None,
10509 }
10510 }
10511
10512 pub fn parse(alias: &str) -> Option<Self> {
10520 if alias.eq_ignore_ascii_case("ms") && alias != "MS" {
10530 return Some(Self::Milliseconds);
10531 }
10532 match alias.to_ascii_uppercase().as_str() {
10533 "A" | "Y" | "ANNUAL" | "YEARLY" => Some(Self::ANNUAL),
10534 "Q" | "QUARTERLY" => Some(Self::QUARTERLY),
10535 "M" | "MONTHLY" => Some(Self::Monthly),
10536 "W" | "WEEKLY" => Some(Self::WEEKLY),
10537 "D" | "DAILY" => Some(Self::Daily),
10538 "B" | "BUSINESS" => Some(Self::Business),
10539 "H" | "HOURLY" => Some(Self::Hourly),
10540 "T" | "MIN" | "MINUTELY" => Some(Self::Minutely),
10541 "S" | "SECONDLY" => Some(Self::Secondly),
10542 "US" | "MICROSECOND" | "MICROSECONDS" => Some(Self::Microseconds),
10543 "NS" | "NANOSECOND" | "NANOSECONDS" => Some(Self::Nanoseconds),
10544 "MILLISECOND" | "MILLISECONDS" => Some(Self::Milliseconds),
10547 anchored => Self::parse_anchored(anchored),
10548 }
10549 }
10550
10551 #[must_use]
10553 pub const fn alias(self) -> &'static str {
10554 const ANNUAL: [&str; 12] = [
10555 "Y-JAN", "Y-FEB", "Y-MAR", "Y-APR", "Y-MAY", "Y-JUN", "Y-JUL", "Y-AUG", "Y-SEP",
10556 "Y-OCT", "Y-NOV", "Y-DEC",
10557 ];
10558 const QUARTERLY: [&str; 12] = [
10559 "Q-JAN", "Q-FEB", "Q-MAR", "Q-APR", "Q-MAY", "Q-JUN", "Q-JUL", "Q-AUG", "Q-SEP",
10560 "Q-OCT", "Q-NOV", "Q-DEC",
10561 ];
10562 const WEEKLY: [&str; 7] = [
10563 "W-MON", "W-TUE", "W-WED", "W-THU", "W-FRI", "W-SAT", "W-SUN",
10564 ];
10565 match self {
10566 Self::Annual(month) => ANNUAL[(month as usize + 11) % 12],
10567 Self::Quarterly(month) => QUARTERLY[(month as usize + 11) % 12],
10568 Self::Monthly => "M",
10569 Self::Weekly(day) => WEEKLY[day as usize % 7],
10570 Self::Daily => "D",
10571 Self::Business => "B",
10572 Self::Hourly => "h",
10573 Self::Minutely => "min",
10574 Self::Secondly => "s",
10575 Self::Milliseconds => "ms",
10576 Self::Microseconds => "us",
10577 Self::Nanoseconds => "ns",
10578 }
10579 }
10580
10581 #[must_use]
10600 pub const fn resolution(self) -> Option<&'static str> {
10601 match self {
10602 Self::Annual(_) => Some("year"),
10603 Self::Quarterly(_) => Some("quarter"),
10604 Self::Monthly => Some("month"),
10605 Self::Daily => Some("day"),
10606 Self::Hourly => Some("hour"),
10607 Self::Minutely => Some("minute"),
10608 Self::Secondly => Some("second"),
10609 Self::Milliseconds => Some("millisecond"),
10610 Self::Microseconds => Some("microsecond"),
10611 Self::Nanoseconds => Some("nanosecond"),
10612 Self::Weekly(_) | Self::Business => None,
10615 }
10616 }
10617}
10618
10619impl std::fmt::Display for PeriodFreq {
10620 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
10621 f.write_str(self.alias())
10622 }
10623}
10624
10625#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
10633pub struct Period {
10634 pub ordinal: i64,
10635 pub freq: PeriodFreq,
10636}
10637
10638impl Period {
10639 #[must_use]
10640 pub const fn new(ordinal: i64, freq: PeriodFreq) -> Self {
10641 Self { ordinal, freq }
10642 }
10643
10644 #[must_use]
10647 pub const fn is_nat(&self) -> bool {
10648 self.ordinal == i64::MIN
10649 }
10650
10651 #[must_use]
10654 pub const fn ordinal(&self) -> i64 {
10655 self.ordinal
10656 }
10657
10658 #[must_use]
10660 pub const fn freq(&self) -> PeriodFreq {
10661 self.freq
10662 }
10663
10664 #[must_use]
10666 pub const fn freqstr(&self) -> &'static str {
10667 self.freq.alias()
10668 }
10669
10670 #[must_use]
10673 pub fn cmp_same_freq(&self, other: &Self) -> Option<std::cmp::Ordering> {
10674 if self.freq != other.freq {
10675 return None;
10676 }
10677 Some(self.ordinal.cmp(&other.ordinal))
10678 }
10679
10680 #[must_use]
10683 pub fn shift(&self, n: i64) -> Self {
10684 Self {
10685 ordinal: self.ordinal.saturating_add(n),
10686 freq: self.freq,
10687 }
10688 }
10689
10690 #[must_use]
10693 pub fn diff(&self, other: &Self) -> Option<i64> {
10694 if self.freq != other.freq {
10695 return None;
10696 }
10697 Some(self.ordinal.saturating_sub(other.ordinal))
10698 }
10699
10700 pub fn parse(s: &str) -> Result<Self, TypeError> {
10707 let trimmed = s.trim();
10708 if trimmed.eq_ignore_ascii_case("nat") {
10709 return Ok(Self::new(i64::MIN, PeriodFreq::Daily));
10710 }
10711
10712 if let Some((year, quarter)) = parse_quarter_period(trimmed) {
10713 let ordinal = year
10714 .checked_sub(1970)
10715 .and_then(|offset| offset.checked_mul(4))
10716 .and_then(|base| base.checked_add(i64::from(quarter) - 1))
10717 .ok_or_else(|| TypeError::ValueNotParseable {
10718 value: s.to_owned(),
10719 target: "Period".to_owned(),
10720 })?;
10721 return Ok(Self::new(ordinal, PeriodFreq::QUARTERLY));
10722 }
10723
10724 if let Some((year, month, day)) = parse_ymd_period(trimmed) {
10725 let ordinal = Timestamp::days_from_ymd(year, i64::from(month), i64::from(day));
10726 return Ok(Self::new(ordinal, PeriodFreq::Daily));
10727 }
10728
10729 if let Some((year, month)) = parse_year_month_period(trimmed) {
10730 let ordinal = year
10731 .checked_sub(1970)
10732 .and_then(|offset| offset.checked_mul(12))
10733 .and_then(|base| base.checked_add(i64::from(month) - 1))
10734 .ok_or_else(|| TypeError::ValueNotParseable {
10735 value: s.to_owned(),
10736 target: "Period".to_owned(),
10737 })?;
10738 return Ok(Self::new(ordinal, PeriodFreq::Monthly));
10739 }
10740
10741 if let Some(year) = parse_annual_period(trimmed) {
10742 let ordinal = year
10743 .checked_sub(1970)
10744 .ok_or_else(|| TypeError::ValueNotParseable {
10745 value: s.to_owned(),
10746 target: "Period".to_owned(),
10747 })?;
10748 return Ok(Self::new(ordinal, PeriodFreq::ANNUAL));
10749 }
10750
10751 Err(TypeError::ValueNotParseable {
10752 value: s.to_owned(),
10753 target: "Period".to_owned(),
10754 })
10755 }
10756
10757 #[must_use]
10782 pub fn calendar_string(&self) -> String {
10783 let mut rendered = String::new();
10784 let _ = self.write_calendar(&mut rendered);
10786 rendered
10787 }
10788
10789 fn write_calendar(&self, rendered: &mut impl std::fmt::Write) -> std::fmt::Result {
10790 if self.ordinal == i64::MIN {
10791 return rendered.write_str("NaT");
10792 }
10793 let ord = self.ordinal;
10794 match self.freq {
10795 PeriodFreq::Annual(_) => {
10799 let year = 1970 + ord;
10800 write!(rendered, "{year}")
10801 }
10802 PeriodFreq::Quarterly(_) => {
10803 let year = 1970 + ord.div_euclid(4);
10804 let quarter = ord.rem_euclid(4) + 1;
10805 write!(rendered, "{year}Q{quarter}")
10806 }
10807 PeriodFreq::Monthly => {
10808 let year = 1970 + ord.div_euclid(12);
10809 let month = ord.rem_euclid(12) + 1;
10810 write!(rendered, "{year:04}-{month:02}")
10811 }
10812 PeriodFreq::Daily => {
10813 let (y, m, d) = civil_from_days(ord);
10814 write!(rendered, "{y:04}-{m:02}-{d:02}")
10815 }
10816 PeriodFreq::Business => {
10827 const WEEKDAY_OFFSET: [i64; 5] = [0, 1, 4, 5, 6];
10828 let offset = WEEKDAY_OFFSET[ord.rem_euclid(5) as usize];
10831 let days = ord.div_euclid(5).saturating_mul(7).saturating_add(offset);
10832 let (y, m, d) = civil_from_days(days);
10833 write!(rendered, "{y:04}-{m:02}-{d:02}")
10834 }
10835 PeriodFreq::Weekly(_) => {
10845 const WEEK_ANCHOR_DAY: i64 = -10;
10849 let start = ord
10850 .saturating_mul(7)
10851 .saturating_add(WEEK_ANCHOR_DAY + self.freq.week_start_shift());
10852 let (sy, sm, sd) = civil_from_days(start);
10853 let (ey, em, ed) = civil_from_days(start.saturating_add(6));
10854 write!(rendered, "{sy:04}-{sm:02}-{sd:02}/{ey:04}-{em:02}-{ed:02}")
10855 }
10856 PeriodFreq::Hourly => {
10857 let (y, m, d) = civil_from_days(ord.div_euclid(24));
10858 let hour = ord.rem_euclid(24);
10859 write!(rendered, "{y:04}-{m:02}-{d:02} {hour:02}:00")
10860 }
10861 PeriodFreq::Minutely => {
10862 let day = ord.div_euclid(1440);
10863 let mins = ord.rem_euclid(1440);
10864 let (y, m, d) = civil_from_days(day);
10865 write!(
10866 rendered,
10867 "{y:04}-{m:02}-{d:02} {:02}:{:02}",
10868 mins / 60,
10869 mins % 60
10870 )
10871 }
10872 PeriodFreq::Secondly => {
10873 let day = ord.div_euclid(86_400);
10874 let secs = ord.rem_euclid(86_400);
10875 let (y, m, d) = civil_from_days(day);
10876 write!(
10877 rendered,
10878 "{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02}",
10879 secs / 3600,
10880 (secs % 3600) / 60,
10881 secs % 60
10882 )
10883 }
10884 PeriodFreq::Milliseconds | PeriodFreq::Microseconds | PeriodFreq::Nanoseconds => {
10891 let (per_sec, width) = match self.freq {
10892 PeriodFreq::Milliseconds => (1_000_i64, 3_usize),
10893 PeriodFreq::Microseconds => (1_000_000_i64, 6_usize),
10894 _ => (1_000_000_000_i64, 9_usize),
10895 };
10896 let per_day = 86_400 * per_sec;
10898 let day = ord.div_euclid(per_day);
10899 let rest = ord.rem_euclid(per_day);
10900 let secs = rest / per_sec;
10901 let frac = rest % per_sec;
10902 let (y, m, d) = civil_from_days(day);
10903 write!(
10904 rendered,
10905 "{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02}.{:0width$}",
10906 secs / 3600,
10907 (secs % 3600) / 60,
10908 secs % 60,
10909 frac,
10910 width = width
10911 )
10912 }
10913 }
10914 }
10915}
10916
10917#[must_use]
10922pub fn civil_from_days(days_since_epoch: i64) -> (i64, u32, u32) {
10923 let days = days_since_epoch + 719_468;
10924 let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
10925 let doe = days - era * 146_097;
10926 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
10927 let y = yoe + era * 400;
10928 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
10929 let mp = (5 * doy + 2) / 153;
10930 let d = doy - (153 * mp + 2) / 5 + 1;
10931 let m = if mp < 10 { mp + 3 } else { mp - 9 };
10932 let year = if m <= 2 { y + 1 } else { y };
10933 (year, m as u32, d as u32)
10934}
10935
10936fn parse_annual_period(value: &str) -> Option<i64> {
10937 (value.len() == 4 && value.chars().all(|ch| ch.is_ascii_digit()))
10938 .then(|| value.parse::<i64>().ok())
10939 .flatten()
10940}
10941
10942fn parse_year_month_period(value: &str) -> Option<(i64, u32)> {
10943 let (year, month) = value.split_once('-')?;
10944 if year.len() != 4 || month.len() != 2 {
10945 return None;
10946 }
10947 let year = year.parse::<i64>().ok()?;
10948 let month = month.parse::<u32>().ok()?;
10949 (1..=12).contains(&month).then_some((year, month))
10950}
10951
10952fn parse_ymd_period(value: &str) -> Option<(i64, u32, u32)> {
10953 let mut parts = value.split('-');
10954 let year = parts.next()?;
10955 let month = parts.next()?;
10956 let day = parts.next()?;
10957 if parts.next().is_some() || year.len() != 4 || month.len() != 2 || day.len() != 2 {
10958 return None;
10959 }
10960 let year = year.parse::<i64>().ok()?;
10961 let month = month.parse::<u32>().ok()?;
10962 let day = day.parse::<u32>().ok()?;
10963 (1..=days_in_month(year, month)?)
10964 .contains(&day)
10965 .then_some((year, month, day))
10966}
10967
10968fn parse_quarter_period(value: &str) -> Option<(i64, u32)> {
10969 let (year, quarter) = value.split_once('Q').or_else(|| value.split_once('q'))?;
10970 if year.len() != 4 || quarter.len() != 1 {
10971 return None;
10972 }
10973 let year = year.parse::<i64>().ok()?;
10974 let quarter = quarter.parse::<u32>().ok()?;
10975 (1..=4).contains(&quarter).then_some((year, quarter))
10976}
10977
10978impl std::fmt::Display for Period {
10979 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
10982 self.write_calendar(f)
10983 }
10984}
10985
10986#[must_use]
11005pub fn period_range(start: Period, periods: usize) -> Vec<Period> {
11006 (0..periods).map(|i| start.shift(i as i64)).collect()
11007}
11008
11009#[cfg(test)]
11010mod tests {
11011 use super::{
11012 DType, Interval, IntervalClosed, NullKind, Period, PeriodFreq, Scalar, SparseDType,
11013 cast_scalar, common_dtype, infer_dtype,
11014 };
11015
11016 struct Named(&'static str);
11019
11020 impl super::HostObject for Named {
11021 fn host_eq(&self, other: &dyn super::HostObject) -> bool {
11022 other
11023 .as_any()
11024 .downcast_ref::<Named>()
11025 .is_some_and(|other| other.0 == self.0)
11026 }
11027 fn host_repr(&self) -> String {
11028 format!("Named({:?})", self.0)
11029 }
11030 fn host_str(&self) -> String {
11031 self.0.to_owned()
11032 }
11033 fn host_hash(&self) -> Option<u64> {
11034 (!self.0.is_empty()).then_some(self.0.len() as u64)
11035 }
11036 fn host_cmp(&self, other: &dyn super::HostObject) -> Option<std::cmp::Ordering> {
11038 let other = other.as_any().downcast_ref::<Named>()?;
11039 (!self.0.starts_with('!') && !other.0.starts_with('!')).then(|| self.0.cmp(other.0))
11040 }
11041 fn as_any(&self) -> &dyn std::any::Any {
11042 self
11043 }
11044 }
11045
11046 #[test]
11047 fn host_values_block_workers_only_under_a_declared_host_lock_4qg5w_13() {
11048 use std::sync::atomic::Ordering;
11049
11050 use super::{HostValue, LIVE_HOST_VALUES, workers_blocked};
11051 assert!(workers_blocked(true, 1));
11055 assert!(!workers_blocked(true, 0));
11056 assert!(!workers_blocked(false, 3));
11057 let first = HostValue::new(Named("held"));
11062 assert!(LIVE_HOST_VALUES.load(Ordering::Relaxed) > 0);
11063 let clone = first.clone();
11064 drop(first);
11065 assert!(LIVE_HOST_VALUES.load(Ordering::Relaxed) > 0);
11066 assert_eq!(clone.object().host_str(), "held");
11067 }
11068
11069 #[test]
11070 fn object_cells_order_like_python_then_totally_fvsao_66() {
11071 use std::cmp::Ordering;
11072
11073 use super::{HostValue, ObjectValue};
11074 let host = |name: &'static str| ObjectValue::Host(HostValue::new(Named(name)));
11075 let list = |items: Vec<Scalar>| ObjectValue::list(items);
11076 assert_eq!(host("a").python_cmp(&host("b")), Some(Ordering::Less));
11079 assert!(host("b") > host("a"));
11080 assert_eq!(host("a").cmp(&host("a")), Ordering::Equal);
11081 let one_ten = list(vec![Scalar::Int64(1), Scalar::Int64(10)]);
11084 let one_two = list(vec![Scalar::Int64(1), Scalar::Int64(2)]);
11085 assert_eq!(one_two.python_cmp(&one_ten), Some(Ordering::Less));
11086 assert!(list(vec![Scalar::Int64(1)]) < one_two);
11087 let mixed = list(vec![Scalar::Float64(1.0), Scalar::Int64(3)]);
11089 assert_eq!(one_two.python_cmp(&mixed), Some(Ordering::Less));
11090 assert_eq!(one_two.python_cmp(&host("a")), None);
11093 assert!(one_two < host("a"));
11094 assert_eq!(host("!z").python_cmp(&host("!a")), None);
11095 assert!(host("!a") < host("!z"));
11096 let text = list(vec![Scalar::Utf8("a".to_owned())]);
11097 assert_eq!(one_two.python_cmp(&text), None);
11098 assert_ne!(one_two.cmp(&text), Ordering::Equal);
11099 let nan = || list(vec![Scalar::Float64(f64::NAN)]);
11102 let (first, second) = (nan(), nan());
11103 assert_ne!(first, second);
11104 assert_ne!(first.cmp(&second), Ordering::Equal);
11105 assert_eq!(first.cmp(&second), second.cmp(&first).reverse());
11106 }
11107
11108 #[test]
11109 fn bytes_cells_print_order_and_serialize_like_python_bytes_4qg5w_8() {
11110 use std::cmp::Ordering;
11111
11112 use super::ObjectValue;
11113 let bytes = |data: &[u8]| Scalar::Object(ObjectValue::bytes(data.to_vec()));
11114 assert_eq!(bytes(b"ab").python_repr(), "b'ab'");
11117 assert_eq!(bytes(b"a'b").python_repr(), "b\"a'b\"");
11118 assert_eq!(bytes(b"a'\"").python_repr(), "b'a\\'\"'");
11119 assert_eq!(bytes(b"\x00\t\\\xff").python_repr(), "b'\\x00\\t\\\\\\xff'");
11120 assert_eq!(bytes(b"ab").python_type_name(), "bytes");
11121 assert_eq!(bytes(b"ab").python_cmp(&bytes(b"b")), Some(Ordering::Less));
11123 assert_eq!(bytes(b"a").python_cmp(&bytes(b"ab")), Some(Ordering::Less));
11124 assert_eq!(bytes(b"a").python_cmp(&Scalar::Utf8("a".to_owned())), None);
11125 assert_ne!(bytes(b"a"), Scalar::Utf8("a".to_owned()));
11126 assert!(!bytes(b"").to_bool().unwrap());
11127 let json = serde_json::to_string(&bytes(b"hi")).unwrap();
11129 assert_eq!(json, r#"{"kind":"object","value":{"bytes":[104,105]}}"#);
11130 let back: Scalar = serde_json::from_str(&json).unwrap();
11131 assert_eq!(back, bytes(b"hi"));
11132 let list: Scalar =
11134 serde_json::from_str(r#"{"kind":"object","value":[{"kind":"int64","value":1}]}"#)
11135 .unwrap();
11136 assert_eq!(
11137 list,
11138 Scalar::Object(ObjectValue::list(vec![Scalar::Int64(1)]))
11139 );
11140 }
11141
11142 #[test]
11143 fn values_order_and_name_their_types_as_python_does_fvsao_71() {
11144 use std::cmp::Ordering;
11145
11146 use super::{HostValue, ObjectValue};
11147 let text = |value: &str| Scalar::Utf8(value.to_owned());
11148 let host =
11149 |name: &'static str| Scalar::Object(ObjectValue::Host(HostValue::new(Named(name))));
11150 let list = |items: Vec<Scalar>| Scalar::Object(ObjectValue::list(items));
11151 assert_eq!(
11154 Scalar::Bool(true).python_cmp(&Scalar::Float64(1.5)),
11155 Some(Ordering::Less)
11156 );
11157 assert_eq!(
11158 Scalar::Int64(2).python_cmp(&Scalar::Float64(2.0)),
11159 Some(Ordering::Equal)
11160 );
11161 assert_eq!(text("b").python_cmp(&text("a")), Some(Ordering::Greater));
11162 assert_eq!(
11163 Scalar::Datetime64(5).python_cmp(&Scalar::Datetime64(9)),
11164 Some(Ordering::Less)
11165 );
11166 let interval = |left: f64, right: f64| {
11167 Scalar::Interval(Interval::new(left, right, IntervalClosed::Right))
11168 };
11169 assert_eq!(
11170 interval(0.0, 5.0).python_cmp(&interval(0.0, 2.0)),
11171 Some(Ordering::Greater)
11172 );
11173 assert_eq!(host("a").python_cmp(&host("b")), Some(Ordering::Less));
11174 assert_eq!(text("a").python_cmp(&Scalar::Int64(1)), None);
11177 assert_eq!(
11178 Scalar::Datetime64(1).python_cmp(&Scalar::Timedelta64(1)),
11179 None
11180 );
11181 assert_eq!(host("a").python_cmp(&Scalar::Int64(1)), None);
11182 assert_eq!(host("!a").python_cmp(&host("b")), None);
11183 assert_eq!(text("a").python_type_name(), "str");
11187 assert_eq!(Scalar::Bool(true).python_type_name(), "bool");
11188 assert_eq!(Scalar::Datetime64(1).python_type_name(), "Timestamp");
11189 assert_eq!(list(vec![]).python_type_name(), "list");
11190 assert_eq!(host("a").python_type_name(), "object");
11191 let (left, right) = list(vec![Scalar::Int64(1), Scalar::Int64(2)])
11192 .python_cmp_type_names(&list(vec![Scalar::Int64(1), text("x")]));
11193 assert_eq!((left.as_str(), right.as_str()), ("int", "str"));
11194 let (left, right) = text("a").python_cmp_type_names(&list(vec![]));
11195 assert_eq!((left.as_str(), right.as_str()), ("str", "list"));
11196 }
11197
11198 #[test]
11199 fn object_cells_print_compare_and_hash_like_python_fvsao_33() {
11200 use std::hash::{Hash, Hasher};
11201
11202 use super::{HostValue, ObjectValue};
11203 let hash = |value: &ObjectValue| {
11204 let mut hasher = std::collections::hash_map::DefaultHasher::new();
11205 value.hash(&mut hasher);
11206 hasher.finish()
11207 };
11208 let list = ObjectValue::list(vec![
11209 Scalar::Int64(1),
11210 Scalar::Utf8("a".to_owned()),
11211 Scalar::Null(NullKind::Null),
11212 Scalar::Float64(2.0),
11213 Scalar::Object(ObjectValue::list(vec![Scalar::Utf8("b".to_owned())])),
11214 ]);
11215 assert_eq!(list.repr(), "[1, 'a', None, 2.0, ['b']]");
11218 assert_eq!(list.to_string(), "[1, 'a', None, 2.0, ['b']]");
11219 assert_eq!(list.pprint(), "[1, a, None, 2.0, [b]]");
11220 assert_eq!(Scalar::Object(list.clone()).dtype(), DType::Utf8);
11222 assert!(!Scalar::Object(list.clone()).is_missing());
11223 let same = ObjectValue::list(list.as_list().unwrap().to_vec());
11226 assert_eq!(list, same);
11227 assert_eq!(hash(&list), hash(&same));
11228 let other = ObjectValue::list(vec![Scalar::Int64(1)]);
11229 assert_ne!(list, other);
11230 let host = ObjectValue::Host(HostValue::new(Named("x")));
11231 assert_ne!(list, host);
11232 assert_eq!(host, ObjectValue::Host(HostValue::new(Named("x"))));
11234 assert_ne!(host, ObjectValue::Host(HostValue::new(Named("y"))));
11235 assert_eq!(host.repr(), "Named(\"x\")");
11236 assert_eq!(host.to_string(), "x");
11237 assert!(
11239 !Scalar::Object(ObjectValue::list(Vec::new()))
11240 .to_bool()
11241 .unwrap()
11242 );
11243 assert!(Scalar::Object(host.clone()).to_bool().unwrap());
11244 assert!(Scalar::Object(list.clone()).to_f64().is_err());
11246 let json = serde_json::to_string(&Scalar::Object(other.clone())).unwrap();
11249 assert_eq!(
11250 serde_json::from_str::<Scalar>(&json).unwrap(),
11251 Scalar::Object(other)
11252 );
11253 assert!(serde_json::to_string(&Scalar::Object(host)).is_err());
11254 }
11255
11256 #[test]
11257 fn a_host_cell_displays_by_its_pprint_and_stringifies_by_its_str() {
11258 use super::{HostValue, ObjectValue};
11259
11260 struct Pair;
11262 impl super::HostObject for Pair {
11263 fn host_eq(&self, _other: &dyn super::HostObject) -> bool {
11264 false
11265 }
11266 fn host_repr(&self) -> String {
11267 "('a', 1)".to_owned()
11268 }
11269 fn host_str(&self) -> String {
11270 "('a', 1)".to_owned()
11271 }
11272 fn host_pprint(&self) -> String {
11273 "(a, 1)".to_owned()
11274 }
11275 fn host_hash(&self) -> Option<u64> {
11276 None
11277 }
11278 fn host_cmp(&self, _other: &dyn super::HostObject) -> Option<std::cmp::Ordering> {
11279 None
11280 }
11281 fn as_any(&self) -> &dyn std::any::Any {
11282 self
11283 }
11284 }
11285 let pair = ObjectValue::Host(HostValue::new(Pair));
11286 assert_eq!(pair.pprint(), "(a, 1)");
11287 let list = ObjectValue::list(vec![Scalar::Object(pair.clone())]);
11289 assert_eq!(list.pprint(), "[(a, 1)]");
11290 assert_eq!(pair.to_string(), "('a', 1)");
11292 let named = ObjectValue::Host(HostValue::new(Named("x")));
11294 assert_eq!(named.pprint(), "x");
11295 }
11296
11297 #[test]
11298 fn float64_json_spells_infinity_and_round_trips() {
11299 let json = |s: &Scalar| serde_json::to_string(s).expect("serialize");
11303 let back = |text: &str| serde_json::from_str::<Scalar>(text);
11304 assert_eq!(
11305 json(&Scalar::Float64(f64::INFINITY)),
11306 r#"{"kind":"float64","value":"inf"}"#
11307 );
11308 assert_eq!(
11309 json(&Scalar::Float64(f64::NEG_INFINITY)),
11310 r#"{"kind":"float64","value":"-inf"}"#
11311 );
11312 assert_eq!(
11314 json(&Scalar::Float64(1.5)),
11315 r#"{"kind":"float64","value":1.5}"#
11316 );
11317 assert_eq!(
11318 json(&Scalar::Float64(-0.0)),
11319 r#"{"kind":"float64","value":-0.0}"#
11320 );
11321 assert_eq!(
11322 json(&Scalar::Float64(f64::NAN)),
11323 r#"{"kind":"float64","value":null}"#
11324 );
11325 for value in [f64::INFINITY, f64::NEG_INFINITY, 1.5, -2.25e300] {
11326 let scalar = Scalar::Float64(value);
11327 assert_eq!(back(&json(&scalar)).expect("round trip"), scalar);
11328 }
11329 let negative_zero = back(r#"{"kind":"float64","value":-0.0}"#).expect("-0.0");
11330 assert!(matches!(negative_zero, Scalar::Float64(v) if v == 0.0 && v.is_sign_negative()));
11331 assert!(matches!(
11332 back(r#"{"kind":"float64","value":null}"#).expect("null"),
11333 Scalar::Float64(v) if v.is_nan()
11334 ));
11335 assert!(back(r#"{"kind":"float64","value":"Infinity"}"#).is_err());
11337 assert!(back(r#"{"kind":"float64","value":"1.5"}"#).is_err());
11338 }
11339
11340 #[test]
11350 fn semantic_cmp_cross_numeric_int_float_cdpai() {
11351 use std::cmp::Ordering;
11354 let mut st: u64 = 0xc205_a1b2_c3d4_e5f6;
11355 let mut next = || {
11356 st = st
11357 .wrapping_mul(6_364_136_223_846_793_005)
11358 .wrapping_add(1_442_695_040_888_963_407);
11359 (st >> 33) as u32
11360 };
11361 for _ in 0..3000u32 {
11362 let i = (next() % 21) as i64 - 10;
11363 let f = (next() % 400) as f64 / 20.0 - 10.0; let exp = (i as f64).partial_cmp(&f).unwrap();
11365 assert_eq!(Scalar::Int64(i).semantic_cmp(&Scalar::Float64(f)), exp);
11366 assert_eq!(
11367 Scalar::Float64(f).semantic_cmp(&Scalar::Int64(i)),
11368 exp.reverse()
11369 );
11370 }
11371 assert_eq!(
11373 Scalar::Int64(5).semantic_cmp(&Scalar::Float64(5.0)),
11374 Ordering::Equal
11375 );
11376 assert_eq!(
11377 Scalar::Float64(5.0).semantic_cmp(&Scalar::Int64(5)),
11378 Ordering::Equal
11379 );
11380 assert_eq!(
11381 Scalar::Int64(3).semantic_cmp(&Scalar::Float64(3.5)),
11382 Ordering::Less
11383 );
11384 assert_eq!(
11385 Scalar::Int64(4).semantic_cmp(&Scalar::Float64(3.5)),
11386 Ordering::Greater
11387 );
11388 }
11389
11390 #[test]
11391 fn semantic_cmp_nat_degeneracy_temporal_767ak() {
11392 use std::cmp::Ordering;
11393 const NAT: i64 = i64::MIN;
11394
11395 let td_nat = Scalar::Timedelta64(NAT);
11397 for v in [-3i64, 0, 5, 99] {
11398 let td = Scalar::Timedelta64(v);
11399 assert_eq!(td_nat.semantic_cmp(&td), Ordering::Equal, "td NAT vs {v}");
11400 assert_eq!(td.semantic_cmp(&td_nat), Ordering::Equal, "td {v} vs NAT");
11401 }
11402 assert_eq!(td_nat.semantic_cmp(&td_nat), Ordering::Equal);
11403
11404 let dt_nat = Scalar::Datetime64(NAT);
11406 for v in [-3i64, 0, 5, 99] {
11407 let dt = Scalar::Datetime64(v);
11408 assert_eq!(dt_nat.semantic_cmp(&dt), Ordering::Equal, "dt NAT vs {v}");
11409 assert_eq!(dt.semantic_cmp(&dt_nat), Ordering::Equal, "dt {v} vs NAT");
11410 }
11411 assert_eq!(dt_nat.semantic_cmp(&dt_nat), Ordering::Equal);
11412
11413 for (a, b) in [(1i64, 2i64), (5, 5), (9, -1)] {
11415 let (ta, tb) = (Scalar::Timedelta64(a), Scalar::Timedelta64(b));
11416 assert_eq!(ta.semantic_cmp(&ta), Ordering::Equal);
11417 assert_eq!(ta.semantic_cmp(&tb), b.cmp(&a).reverse()); assert_eq!(ta.semantic_cmp(&tb), a.cmp(&b));
11419 let (da, db) = (Scalar::Datetime64(a), Scalar::Datetime64(b));
11420 assert_eq!(da.semantic_cmp(&db), a.cmp(&b));
11421 }
11422 }
11423
11424 fn semantic_cmp_cross_variant_values_d5ikg() -> [Scalar; 9] {
11425 [
11426 Scalar::Null(NullKind::Null),
11427 Scalar::Bool(true),
11428 Scalar::Int64(-7),
11429 Scalar::Float64(3.5),
11430 Scalar::Utf8("mixed".to_owned()),
11431 Scalar::Timedelta64(11),
11432 Scalar::Datetime64(1_735_732_800_123_456_789),
11433 Scalar::Period(Period::new(649, PeriodFreq::Monthly)),
11434 Scalar::Interval(Interval::new(-1.5, 2.5, IntervalClosed::Right)),
11435 ]
11436 }
11437
11438 fn semantic_cmp_uses_debug_fallback_d5ikg(left: &Scalar, right: &Scalar) -> bool {
11439 !matches!(
11440 (left, right),
11441 (Scalar::Int64(_), Scalar::Float64(_)) | (Scalar::Float64(_), Scalar::Int64(_))
11442 )
11443 }
11444
11445 #[test]
11446 fn semantic_cmp_cross_variant_matches_debug_order_d5ikg() {
11447 let values = semantic_cmp_cross_variant_values_d5ikg();
11448 for (left_index, left) in values.iter().enumerate() {
11449 for (right_index, right) in values.iter().enumerate() {
11450 if left_index != right_index && semantic_cmp_uses_debug_fallback_d5ikg(left, right)
11451 {
11452 assert_eq!(
11453 left.semantic_cmp(right),
11454 format!("{left:?}").cmp(&format!("{right:?}")),
11455 "cross-variant order mismatch: {left:?} vs {right:?}"
11456 );
11457 }
11458 }
11459 }
11460 }
11461
11462 #[test]
11463 #[ignore = "foreground release attribution harness"]
11464 fn semantic_cmp_cross_variant_debug_alloc_ab_d5ikg() {
11465 use std::cmp::Ordering;
11466
11467 const BATCH: usize = 4_096;
11468 const BLOCKS: usize = 9;
11469
11470 fn former(left: &Scalar, right: &Scalar) -> Ordering {
11471 format!("{left:?}").cmp(&format!("{right:?}"))
11472 }
11473
11474 fn candidate(left: &Scalar, right: &Scalar) -> Ordering {
11475 left.semantic_cmp(right)
11476 }
11477
11478 fn elapsed(values: &[Scalar], compare: fn(&Scalar, &Scalar) -> Ordering) -> u128 {
11479 let mut less = 0usize;
11480 let started = std::time::Instant::now();
11481 for _ in 0..BATCH {
11482 for (left_index, left) in values.iter().enumerate() {
11483 for (right_index, right) in values.iter().enumerate() {
11484 if left_index != right_index
11485 && semantic_cmp_uses_debug_fallback_d5ikg(left, right)
11486 && compare(std::hint::black_box(left), std::hint::black_box(right))
11487 == Ordering::Less
11488 {
11489 less += 1;
11490 }
11491 }
11492 }
11493 }
11494 std::hint::black_box(less);
11495 started.elapsed().as_nanos()
11496 }
11497
11498 fn median(samples: &mut [u128]) -> u128 {
11499 samples.sort_unstable();
11500 samples[samples.len() / 2]
11501 }
11502
11503 let values = semantic_cmp_cross_variant_values_d5ikg();
11504
11505 for (left_index, left) in values.iter().enumerate() {
11506 for (right_index, right) in values.iter().enumerate() {
11507 if left_index != right_index && semantic_cmp_uses_debug_fallback_d5ikg(left, right)
11508 {
11509 assert_eq!(
11510 former(left, right),
11511 candidate(left, right),
11512 "cross-variant order mismatch: {left:?} vs {right:?}"
11513 );
11514 }
11515 }
11516 }
11517
11518 std::hint::black_box(elapsed(&values, former));
11519 std::hint::black_box(elapsed(&values, candidate));
11520
11521 let mut former_samples = Vec::with_capacity(BLOCKS * 2);
11522 let mut candidate_samples = Vec::with_capacity(BLOCKS * 2);
11523 for block in 0..BLOCKS {
11524 if block.is_multiple_of(2) {
11525 former_samples.push(elapsed(&values, former));
11526 candidate_samples.push(elapsed(&values, candidate));
11527 candidate_samples.push(elapsed(&values, candidate));
11528 former_samples.push(elapsed(&values, former));
11529 } else {
11530 candidate_samples.push(elapsed(&values, candidate));
11531 former_samples.push(elapsed(&values, former));
11532 former_samples.push(elapsed(&values, former));
11533 candidate_samples.push(elapsed(&values, candidate));
11534 }
11535 }
11536
11537 let former_p50 = median(&mut former_samples);
11538 let candidate_p50 = median(&mut candidate_samples);
11539 eprintln!(
11540 "semantic_cmp_cross_variant_debug_alloc former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} speedup={:.6}",
11541 former_p50 as f64 / candidate_p50 as f64
11542 );
11543 }
11544
11545 #[test]
11546 fn semantic_cmp_total_order_axioms_ay8o9() {
11547 use std::cmp::Ordering;
11548
11549 let mut state: u64 = 0xc0ff_eeba_df00_d123;
11550 let mut next = || {
11551 state = state
11552 .wrapping_mul(6_364_136_223_846_793_005)
11553 .wrapping_add(1_442_695_040_888_963_407);
11554 (state >> 33) as u32
11555 };
11556
11557 for iter in 0..6000u32 {
11558 let dt = next() % 4;
11559 let mk = |r: u32| match dt {
11561 0 => Scalar::Int64((r % 11) as i64 - 5),
11562 1 => Scalar::Float64(f64::from((r % 21) as i32 - 10) / 2.0),
11564 2 => Scalar::Utf8(format!("s{}", r % 5)),
11565 _ => Scalar::Bool(r.is_multiple_of(2)),
11566 };
11567 let a = mk(next());
11568 let b = mk(next());
11569 let c = mk(next());
11570 let ctx = format!("iter={iter} a={a:?} b={b:?} c={c:?}");
11571
11572 assert_eq!(a.semantic_cmp(&a), Ordering::Equal, "reflexive {ctx}");
11574 assert_eq!(
11576 a.semantic_cmp(&b),
11577 b.semantic_cmp(&a).reverse(),
11578 "antisymmetric {ctx}"
11579 );
11580 let ab = a.semantic_cmp(&b);
11582 assert_eq!(
11583 a.semantic_le(&b),
11584 ab != Ordering::Greater,
11585 "le-consistent {ctx}"
11586 );
11587 assert_eq!(
11588 a.semantic_ge(&b),
11589 ab != Ordering::Less,
11590 "ge-consistent {ctx}"
11591 );
11592 assert_eq!(
11593 a.semantic_le(&b) && a.semantic_ge(&b),
11594 ab == Ordering::Equal,
11595 "le&ge<=>eq {ctx}"
11596 );
11597 if a.semantic_cmp(&b) != Ordering::Greater && b.semantic_cmp(&c) != Ordering::Greater {
11599 assert_ne!(a.semantic_cmp(&c), Ordering::Greater, "transitivity {ctx}");
11600 }
11601 }
11602
11603 let nan = Scalar::Float64(f64::NAN);
11607 for v in [
11608 Scalar::Float64(-3.5),
11609 Scalar::Float64(0.0),
11610 Scalar::Float64(7.25),
11611 ] {
11612 assert_eq!(nan.semantic_cmp(&v), Ordering::Equal, "NaN cmp finite");
11613 assert_eq!(v.semantic_cmp(&nan), Ordering::Equal, "finite cmp NaN");
11614 }
11615 assert_eq!(nan.semantic_cmp(&nan), Ordering::Equal, "NaN cmp NaN");
11616 }
11617
11618 #[test]
11624 fn common_dtype_lattice_axioms_be314() {
11625 let all: [DType; 14] = [
11626 DType::Null,
11627 DType::Bool,
11628 DType::BoolNullable,
11629 DType::Int64,
11630 DType::Int64Nullable,
11631 DType::Float64,
11632 DType::Float64Nullable,
11635 DType::Utf8,
11636 DType::Categorical,
11637 DType::Timedelta64,
11638 DType::datetime64_naive(),
11639 DType::Period,
11640 DType::Interval,
11641 DType::Sparse,
11642 ];
11643
11644 for a in &all {
11645 assert_eq!(
11647 common_dtype(a.clone(), a.clone()),
11648 Ok(a.clone()),
11649 "idempotent {a:?}"
11650 );
11651 assert_eq!(
11653 common_dtype(DType::Null, a.clone()),
11654 Ok(a.clone()),
11655 "null-left identity {a:?}"
11656 );
11657 assert_eq!(
11658 common_dtype(a.clone(), DType::Null),
11659 Ok(a.clone()),
11660 "null-right identity {a:?}"
11661 );
11662
11663 for b in &all {
11664 assert_eq!(
11667 common_dtype(a.clone(), b.clone()).ok(),
11668 common_dtype(b.clone(), a.clone()).ok(),
11669 "commutative value {a:?},{b:?}"
11670 );
11671 assert_eq!(
11672 common_dtype(a.clone(), b.clone()).is_ok(),
11673 common_dtype(b.clone(), a.clone()).is_ok(),
11674 "commutative ok-ness {a:?},{b:?}"
11675 );
11676 }
11677 }
11678
11679 for a in &all {
11682 for b in &all {
11683 for c in &all {
11684 if let (Ok(ab), Ok(bc)) = (
11685 common_dtype(a.clone(), b.clone()),
11686 common_dtype(b.clone(), c.clone()),
11687 ) && let (Ok(left), Ok(right)) =
11688 (common_dtype(ab, c.clone()), common_dtype(a.clone(), bc))
11689 {
11690 assert_eq!(left, right, "associative {a:?},{b:?},{c:?}");
11691 }
11692 }
11693 }
11694 }
11695 }
11696
11697 #[test]
11700 fn infer_dtype_coercion_rules_e3sfq() {
11701 use DType::{Bool, Float64, Int64, Null, Utf8};
11702
11703 assert_eq!(infer_dtype(&[]), Ok(Null));
11705 assert_eq!(
11706 infer_dtype(&[Scalar::Null(NullKind::Null), Scalar::Null(NullKind::NaN)]),
11707 Ok(Null)
11708 );
11709
11710 let mut s: u64 = 0x132d_a7e0_0e3f_c0de;
11712 let mut next = || {
11713 s = s
11714 .wrapping_mul(6_364_136_223_846_793_005)
11715 .wrapping_add(1_442_695_040_888_963_407);
11716 (s >> 33) as u32
11717 };
11718 for _ in 0..600u32 {
11719 let n = (next() % 6) as usize + 1;
11720 let ints: Vec<Scalar> = (0..n)
11721 .map(|_| Scalar::Int64((next() % 9) as i64 - 4))
11722 .collect();
11723 assert_eq!(infer_dtype(&ints), Ok(Int64));
11724 let floats: Vec<Scalar> = (0..n)
11725 .map(|_| Scalar::Float64(f64::from((next() % 7) as i32)))
11726 .collect();
11727 assert_eq!(infer_dtype(&floats), Ok(Float64));
11728 let bools: Vec<Scalar> = (0..n).map(|_| Scalar::Bool(next() % 2 == 0)).collect();
11729 assert_eq!(infer_dtype(&bools), Ok(Bool));
11730 let strs: Vec<Scalar> = (0..n)
11731 .map(|_| Scalar::Utf8(format!("s{}", next() % 4)))
11732 .collect();
11733 assert_eq!(infer_dtype(&strs), Ok(Utf8));
11734 }
11735
11736 assert_eq!(
11738 infer_dtype(&[
11739 Scalar::Int64(1),
11740 Scalar::Null(NullKind::Null),
11741 Scalar::Int64(2)
11742 ]),
11743 Ok(Int64),
11744 "Int64 + nulls -> Int64"
11745 );
11746 assert_eq!(
11747 infer_dtype(&[Scalar::Int64(1), Scalar::Float64(2.5)]),
11748 Ok(Float64),
11749 "Int64 + Float64 -> Float64"
11750 );
11751 assert_eq!(
11755 infer_dtype(&[Scalar::Bool(true), Scalar::Int64(3)]),
11756 Ok(Utf8),
11757 "Bool + Int64 -> object bucket (pandas constructs object)"
11758 );
11759 assert_eq!(
11760 infer_dtype(&[Scalar::Utf8("a".into()), Scalar::Int64(3)]),
11761 Ok(Utf8),
11762 "Utf8 + Int64 -> Utf8 (object fallback)"
11763 );
11764 }
11765
11766 #[test]
11771 fn missing_for_dtype_always_missing_1ews0() {
11772 let all: [DType; 14] = [
11773 DType::Null,
11774 DType::Bool,
11775 DType::BoolNullable,
11776 DType::Int64,
11777 DType::Int64Nullable,
11778 DType::Float64,
11779 DType::Float64Nullable,
11780 DType::Utf8,
11781 DType::Categorical,
11782 DType::Timedelta64,
11783 DType::datetime64_naive(),
11784 DType::Period,
11785 DType::Interval,
11786 DType::Sparse,
11787 ];
11788 for dt in &all {
11789 let m = Scalar::missing_for_dtype(dt.clone());
11790 assert!(m.is_missing(), "missing_for_dtype({dt:?}) must be missing");
11791 for target in &all {
11792 let cast = cast_scalar(&m, target.clone()).expect("cast of missing");
11793 if target == &DType::Utf8 {
11794 assert!(
11797 matches!(cast, Scalar::Utf8(_)),
11798 "cast(missing {dt:?} -> Utf8) yields a string, got {cast:?}"
11799 );
11800 } else if matches!(dt, DType::Timedelta64 | DType::Datetime64 { .. })
11801 && matches!(target, DType::Bool | DType::Int64)
11802 {
11803 match target {
11819 DType::Bool => assert_eq!(
11820 cast,
11821 Scalar::Bool(true),
11822 "cast(missing {dt:?} -> Bool) is pandas' nonzero-truthy \
11823 read of the NaT bits"
11824 ),
11825 _ => assert_eq!(
11826 cast,
11827 Scalar::Int64(i64::MIN),
11828 "cast(missing {dt:?} -> Int64) is the NaT sentinel itself"
11829 ),
11830 }
11831 } else {
11832 assert!(
11835 cast.is_missing(),
11836 "cast(missing {dt:?} -> {target:?}) must stay missing, got {cast:?}"
11837 );
11838 }
11839 }
11840 }
11841 }
11842
11843 #[test]
11844 fn cast_scalar_bool_int_roundtrip_6w07b() {
11845 use super::cast_scalar;
11846 assert_eq!(
11848 cast_scalar(&Scalar::Bool(true), DType::Int64).unwrap(),
11849 Scalar::Int64(1)
11850 );
11851 assert_eq!(
11852 cast_scalar(&Scalar::Bool(false), DType::Int64).unwrap(),
11853 Scalar::Int64(0)
11854 );
11855 assert_eq!(
11856 cast_scalar(&Scalar::Int64(0), DType::Bool).unwrap(),
11857 Scalar::Bool(false)
11858 );
11859 let mut st: u64 = 0x4b07_0b1c_2d3e_4f50;
11860 let mut next = || {
11861 st = st
11862 .wrapping_mul(6_364_136_223_846_793_005)
11863 .wrapping_add(1_442_695_040_888_963_407);
11864 (st >> 33) as u32
11865 };
11866 for _ in 0..2000u32 {
11867 let v = (next() % 21) as i64 - 10;
11868 assert_eq!(
11869 cast_scalar(&Scalar::Int64(v), DType::Bool).unwrap(),
11870 Scalar::Bool(v != 0),
11871 "int->bool v={v}"
11872 );
11873 }
11874 }
11875
11876 #[test]
11878 fn cast_scalar_float_to_int_truncates_toward_zero_u9lec() {
11879 use super::cast_scalar;
11880 let mut st: u64 = 0x4ca5_0b1c_2d3e_4f50;
11883 let mut next = || {
11884 st = st
11885 .wrapping_mul(6_364_136_223_846_793_005)
11886 .wrapping_add(1_442_695_040_888_963_407);
11887 (st >> 33) as u32
11888 };
11889 for (f, exp) in [
11891 (-3.7, -3i64),
11892 (3.7, 3),
11893 (-3.2, -3),
11894 (3.2, 3),
11895 (-0.9, 0),
11896 (0.9, 0),
11897 (-5.0, -5),
11898 (5.0, 5),
11899 ] {
11900 assert_eq!(
11901 cast_scalar(&Scalar::Float64(f), DType::Int64).unwrap(),
11902 Scalar::Int64(exp),
11903 "cast {f}"
11904 );
11905 }
11906 for _ in 0..3000u32 {
11908 let v = (next() % 2_000_001) as f64 / 1000.0 - 1000.0; let got = cast_scalar(&Scalar::Float64(v), DType::Int64).unwrap();
11910 assert_eq!(
11911 got,
11912 Scalar::Int64(v.trunc() as i64),
11913 "trunc-toward-zero v={v}"
11914 );
11915 }
11916 }
11917
11918 #[test]
11927 fn cast_scalar_float_to_temporal_truncates_to_nanoseconds() {
11928 use super::{Timedelta, Timestamp, cast_scalar};
11929
11930 for (input, want) in [
11933 (1.5_f64, 1_i64),
11934 (-1.5, -1),
11935 (0.9, 0),
11936 (-0.9, 0),
11937 (2.5, 2),
11938 (-2.5, -2),
11939 (1.999_999, 1),
11940 (-1.999_999, -1),
11941 (2.0, 2),
11942 (1e18, 1_000_000_000_000_000_000),
11943 ] {
11944 assert_eq!(
11945 cast_scalar(&Scalar::Float64(input), DType::datetime64_naive()).unwrap(),
11946 Scalar::Datetime64(want),
11947 "datetime64 cast of {input}"
11948 );
11949 assert_eq!(
11950 cast_scalar(&Scalar::Float64(input), DType::Timedelta64).unwrap(),
11951 Scalar::Timedelta64(want),
11952 "timedelta64 cast of {input}"
11953 );
11954 }
11955
11956 for input in [
11960 f64::NAN,
11961 f64::INFINITY,
11962 f64::NEG_INFINITY,
11963 1e30,
11964 -1e30,
11965 9.3e18,
11966 -9.3e18,
11967 9_223_372_036_854_775_808.0, -9_223_372_036_854_775_808.0, ] {
11970 assert_eq!(
11971 cast_scalar(&Scalar::Float64(input), DType::datetime64_naive()).unwrap(),
11972 Scalar::Datetime64(Timestamp::NAT),
11973 "datetime64 cast of {input} must be NaT"
11974 );
11975 assert_eq!(
11976 cast_scalar(&Scalar::Float64(input), DType::Timedelta64).unwrap(),
11977 Scalar::Timedelta64(Timedelta::NAT),
11978 "timedelta64 cast of {input} must be NaT"
11979 );
11980 }
11981
11982 let just_inside = 9_223_372_036_854_774_784.0_f64; assert_eq!(
11986 cast_scalar(&Scalar::Float64(just_inside), DType::datetime64_naive()).unwrap(),
11987 Scalar::Datetime64(9_223_372_036_854_774_784),
11988 "the largest representable float must NOT be treated as NaT"
11989 );
11990
11991 assert_eq!(
11994 cast_scalar(&Scalar::Float64(1.5), DType::datetime64_naive()).unwrap(),
11995 Scalar::Datetime64(1)
11996 );
11997 assert_eq!(
11998 cast_scalar(&Scalar::Float64(1.5), DType::Int64).unwrap(),
11999 Scalar::Int64(1),
12000 "the SHARED cast truncates here too; it is the explicit constructor \
12001 that refuses, via Column::new's LossyFloatToInt pre-check"
12002 );
12003 }
12004
12005 #[test]
12010 fn cast_scalar_temporal_to_int64_is_raw_nanoseconds() {
12011 use super::{Timedelta, Timestamp, cast_scalar};
12012
12013 for nanos in [1_710_498_645_123_456_789_i64, 93_784_005_006_007, 0, -1] {
12016 assert_eq!(
12017 cast_scalar(&Scalar::Datetime64(nanos), DType::Int64).unwrap(),
12018 Scalar::Int64(nanos),
12019 "datetime64 -> int64 must be the raw nanos ({nanos})"
12020 );
12021 assert_eq!(
12022 cast_scalar(&Scalar::Timedelta64(nanos), DType::Int64).unwrap(),
12023 Scalar::Int64(nanos)
12024 );
12025 }
12026
12027 assert_eq!(
12033 cast_scalar(&Scalar::Datetime64(Timestamp::NAT), DType::Int64).unwrap(),
12034 Scalar::Int64(i64::MIN),
12035 "NaT -> int64 is the sentinel i64::MIN, not a missing value"
12036 );
12037 assert_eq!(
12038 cast_scalar(&Scalar::Timedelta64(Timedelta::NAT), DType::Int64).unwrap(),
12039 Scalar::Int64(i64::MIN)
12040 );
12041
12042 for target in [DType::Int64Nullable, DType::Float64, DType::Float64Nullable] {
12051 assert!(
12052 cast_scalar(
12053 &Scalar::Datetime64(1_710_498_645_123_456_789),
12054 target.clone()
12055 )
12056 .is_err(),
12057 "datetime64 -> {target:?} must stay refused"
12058 );
12059 assert!(
12060 cast_scalar(&Scalar::Timedelta64(93_784_005_006_007), target.clone()).is_err(),
12061 "timedelta64 -> {target:?} must stay refused"
12062 );
12063 }
12064
12065 for (flag, want) in [(true, 1_i64), (false, 0)] {
12067 assert_eq!(
12068 cast_scalar(&Scalar::Bool(flag), DType::datetime64_naive()).unwrap(),
12069 Scalar::Datetime64(want)
12070 );
12071 assert_eq!(
12072 cast_scalar(&Scalar::Bool(flag), DType::Timedelta64).unwrap(),
12073 Scalar::Timedelta64(want)
12074 );
12075 }
12076 }
12077
12078 #[test]
12082 fn timestamp_string_resolution_and_formatting_match_pandas() {
12083 use super::{DatetimeStringResolution as Res, Timestamp};
12084
12085 const MIDNIGHT: i64 = 1_710_460_800_000_000_000; assert_eq!(Timestamp::string_resolution(MIDNIGHT), Res::Date);
12089 assert_eq!(
12090 Timestamp::string_resolution(MIDNIGHT + 37_845_000_000_000),
12091 Res::Second
12092 );
12093 assert_eq!(
12094 Timestamp::string_resolution(MIDNIGHT + 37_845_123_000_000),
12095 Res::Milli
12096 );
12097 assert_eq!(
12098 Timestamp::string_resolution(MIDNIGHT + 37_845_123_456_000),
12099 Res::Micro
12100 );
12101 assert_eq!(
12102 Timestamp::string_resolution(MIDNIGHT + 37_845_123_456_789),
12103 Res::Nano
12104 );
12105 assert_eq!(
12107 Timestamp::string_resolution(MIDNIGHT + 300_000_000_000),
12108 Res::Second
12109 );
12110 assert_eq!(Timestamp::string_resolution(Timestamp::NAT), Res::Date);
12113
12114 assert!(Res::Date < Res::Second);
12116 assert!(Res::Second < Res::Milli);
12117 assert!(Res::Milli < Res::Micro);
12118 assert!(Res::Micro < Res::Nano);
12119
12120 let value = MIDNIGHT + 37_845_123_456_789;
12122 assert_eq!(
12123 Timestamp::format_at_resolution(value, Res::Date),
12124 "2024-03-15"
12125 );
12126 assert_eq!(
12127 Timestamp::format_at_resolution(value, Res::Second),
12128 "2024-03-15 10:30:45"
12129 );
12130 assert_eq!(
12131 Timestamp::format_at_resolution(value, Res::Milli),
12132 "2024-03-15 10:30:45.123"
12133 );
12134 assert_eq!(
12135 Timestamp::format_at_resolution(value, Res::Micro),
12136 "2024-03-15 10:30:45.123456"
12137 );
12138 assert_eq!(
12139 Timestamp::format_at_resolution(value, Res::Nano),
12140 "2024-03-15 10:30:45.123456789"
12141 );
12142
12143 assert_eq!(
12146 Timestamp::format_at_resolution(MIDNIGHT, Res::Nano),
12147 "2024-03-15 00:00:00.000000000"
12148 );
12149
12150 assert_eq!(
12152 Timestamp::format_at_resolution(MIDNIGHT, Res::Second),
12153 "2024-03-15 00:00:00"
12154 );
12155
12156 for resolution in [Res::Date, Res::Second, Res::Milli, Res::Micro, Res::Nano] {
12158 assert_eq!(
12159 Timestamp::format_at_resolution(Timestamp::NAT, resolution),
12160 "NaT"
12161 );
12162 }
12163
12164 assert_eq!(
12167 Timestamp::format_at_resolution(-1, Res::Nano),
12168 "1969-12-31 23:59:59.999999999"
12169 );
12170
12171 assert_eq!(
12173 Timestamp::format_at_resolution(-9_223_372_036_854_775_806, Res::Nano),
12174 "1677-09-21 00:12:43.145224194"
12175 );
12176 assert_eq!(
12177 Timestamp::format_at_resolution(9_223_372_036_854_775_807, Res::Nano),
12178 "2262-04-11 23:47:16.854775807"
12179 );
12180 }
12181
12182 #[test]
12186 fn cast_scalar_temporal_to_bool_is_nonzero_on_the_nanos() {
12187 use super::{Timedelta, Timestamp, cast_scalar};
12188
12189 for (nanos, want) in [
12191 (0_i64, false),
12192 (1_710_498_645_123_456_789, true),
12193 (-1, true),
12194 (86_400_000_000_000, true),
12195 (1, true),
12196 ] {
12197 assert_eq!(
12198 cast_scalar(&Scalar::Datetime64(nanos), DType::Bool).unwrap(),
12199 Scalar::Bool(want),
12200 "datetime64 {nanos} -> bool"
12201 );
12202 assert_eq!(
12203 cast_scalar(&Scalar::Timedelta64(nanos), DType::Bool).unwrap(),
12204 Scalar::Bool(want),
12205 "timedelta64 {nanos} -> bool"
12206 );
12207 }
12208
12209 assert_eq!(
12213 cast_scalar(&Scalar::Datetime64(Timestamp::NAT), DType::Bool).unwrap(),
12214 Scalar::Bool(true),
12215 "NaT -> bool is true in pandas, not a missing value"
12216 );
12217 assert_eq!(
12218 cast_scalar(&Scalar::Timedelta64(Timedelta::NAT), DType::Bool).unwrap(),
12219 Scalar::Bool(true)
12220 );
12221
12222 for nanos in [0_i64, 1, -1, 1_710_498_645_123_456_789] {
12233 assert!(
12234 cast_scalar(&Scalar::Datetime64(nanos), DType::BoolNullable).is_err(),
12235 "datetime64 {nanos} -> nullable boolean must stay refused"
12236 );
12237 assert!(
12238 cast_scalar(&Scalar::Timedelta64(nanos), DType::BoolNullable).is_err(),
12239 "timedelta64 {nanos} -> nullable boolean must stay refused"
12240 );
12241 }
12242 }
12243
12244 #[test]
12245 fn nancount_nunique_prod_any_all_mx60x() {
12246 use super::{nanall, nanany, nancount, nannunique, nanprod};
12247 let mut s: u64 = 0x4e2a_0b1c_2d3e_4f50;
12250 let mut next = || {
12251 s = s
12252 .wrapping_mul(6_364_136_223_846_793_005)
12253 .wrapping_add(1_442_695_040_888_963_407);
12254 (s >> 33) as u32
12255 };
12256 let asf = |sc: Scalar| -> f64 { sc.to_f64().unwrap_or(f64::NAN) };
12257 let asb = |sc: Scalar| -> bool { matches!(sc, Scalar::Bool(true)) };
12258 for iter in 0..1000u32 {
12259 let n = (next() % 10) as usize + 1;
12260 let raw: Vec<f64> = (0..n)
12261 .map(|_| {
12262 if next() % 4 == 0 {
12263 f64::NAN
12264 } else {
12265 (next() % 5) as f64
12266 }
12267 })
12268 .collect();
12269 let finite: Vec<f64> = raw.iter().copied().filter(|x| !x.is_nan()).collect();
12270 if finite.is_empty() {
12271 continue;
12272 }
12273 let scalars: Vec<Scalar> = raw.iter().map(|&x| Scalar::Float64(x)).collect();
12274 let distinct: std::collections::HashSet<u64> =
12275 finite.iter().map(|x| x.to_bits()).collect();
12276 let prod: f64 = finite.iter().product();
12277 assert!(
12278 (asf(nancount(&scalars)) - finite.len() as f64).abs() < 1e-9,
12279 "nancount iter={iter}"
12280 );
12281 assert!(
12282 (asf(nannunique(&scalars)) - distinct.len() as f64).abs() < 1e-9,
12283 "nannunique iter={iter}"
12284 );
12285 assert!(
12286 (asf(nanprod(&scalars)) - prod).abs() < 1e-7,
12287 "nanprod iter={iter}"
12288 );
12289 assert_eq!(
12290 asb(nanany(&scalars)),
12291 finite.iter().any(|&x| x != 0.0),
12292 "nanany iter={iter}"
12293 );
12294 assert_eq!(
12295 asb(nanall(&scalars)),
12296 finite.iter().all(|&x| x != 0.0),
12297 "nanall iter={iter}"
12298 );
12299 }
12300 }
12301
12302 #[test]
12303 fn nan_reduction_kernels_skip_correctness_1uagc() {
12304 use super::{nanmax, nanmedian, nanmin, nansum};
12305 let mut s: u64 = 0x4e1a_0b2c_2d3e_4f50;
12308 let mut next = || {
12309 s = s
12310 .wrapping_mul(6_364_136_223_846_793_005)
12311 .wrapping_add(1_442_695_040_888_963_407);
12312 (s >> 33) as u32
12313 };
12314 let val = |sc: Scalar| -> f64 { sc.to_f64().unwrap_or(f64::NAN) };
12315 for iter in 0..1000u32 {
12316 let n = (next() % 12) as usize + 1;
12317 let raw: Vec<f64> = (0..n)
12318 .map(|_| {
12319 if next() % 4 == 0 {
12320 f64::NAN
12321 } else {
12322 (next() % 200) as f64 - 100.0
12323 }
12324 })
12325 .collect();
12326 let mut finite: Vec<f64> = raw.iter().copied().filter(|x| !x.is_nan()).collect();
12327 if finite.is_empty() {
12328 continue;
12329 }
12330 let scalars: Vec<Scalar> = raw.iter().map(|&x| Scalar::Float64(x)).collect();
12331 let sum: f64 = finite.iter().sum();
12332 let mn = finite.iter().copied().fold(f64::INFINITY, f64::min);
12333 let mx = finite.iter().copied().fold(f64::NEG_INFINITY, f64::max);
12334 finite.sort_by(|a, b| a.partial_cmp(b).unwrap());
12335 let m = finite.len();
12336 let med = if m % 2 == 1 {
12337 finite[m / 2]
12338 } else {
12339 (finite[m / 2 - 1] + finite[m / 2]) / 2.0
12340 };
12341 assert!(
12342 (val(nansum(&scalars)) - sum).abs() < 1e-7,
12343 "nansum iter={iter}"
12344 );
12345 assert!(
12346 (val(nanmin(&scalars)) - mn).abs() < 1e-9,
12347 "nanmin iter={iter}"
12348 );
12349 assert!(
12350 (val(nanmax(&scalars)) - mx).abs() < 1e-9,
12351 "nanmax iter={iter}"
12352 );
12353 assert!(
12354 (val(nanmedian(&scalars)) - med).abs() < 1e-9,
12355 "nanmedian iter={iter}"
12356 );
12357 }
12358 }
12359
12360 #[test]
12361 fn nanvar_ddof_nanstd_nan_skip_p00ag() {
12362 use super::{nanmean, nanstd, nanvar};
12363 let mut s: u64 = 0x4e0a_0b1c_2d3e_4f50;
12366 let mut next = || {
12367 s = s
12368 .wrapping_mul(6_364_136_223_846_793_005)
12369 .wrapping_add(1_442_695_040_888_963_407);
12370 (s >> 33) as u32
12371 };
12372 let val = |sc: Scalar| -> f64 { sc.to_f64().unwrap_or(f64::NAN) };
12373 for iter in 0..1000u32 {
12374 let n = (next() % 10) as usize + 2;
12375 let raw: Vec<f64> = (0..n)
12376 .map(|_| {
12377 if next() % 4 == 0 {
12378 f64::NAN
12379 } else {
12380 (next() % 200) as f64 / 7.0
12381 }
12382 })
12383 .collect();
12384 let finite: Vec<f64> = raw.iter().copied().filter(|x| !x.is_nan()).collect();
12385 if finite.len() < 2 {
12386 continue;
12387 }
12388 let scalars: Vec<Scalar> = raw.iter().map(|&x| Scalar::Float64(x)).collect();
12389 let nf = finite.len() as f64;
12390 let mean = finite.iter().sum::<f64>() / nf;
12391 let ss = finite.iter().map(|x| (x - mean).powi(2)).sum::<f64>();
12392 assert!(
12393 (val(nanmean(&scalars)) - mean).abs() < 1e-7,
12394 "nanmean iter={iter}"
12395 );
12396 assert!(
12397 (val(nanvar(&scalars, 0)) - ss / nf).abs() < 1e-7,
12398 "nanvar ddof0 iter={iter}"
12399 );
12400 assert!(
12401 (val(nanvar(&scalars, 1)) - ss / (nf - 1.0)).abs() < 1e-7,
12402 "nanvar ddof1 iter={iter}"
12403 );
12404 assert!(
12405 (val(nanstd(&scalars, 1)) - (ss / (nf - 1.0)).sqrt()).abs() < 1e-7,
12406 "nanstd ddof1 iter={iter}"
12407 );
12408 }
12409 }
12410
12411 #[test]
12412 fn nanskew_nankurt_min_sample_and_known_xybnq() {
12413 use super::{nankurt, nanskew};
12416 let f = |xs: &[f64]| -> Vec<Scalar> { xs.iter().map(|&x| Scalar::Float64(x)).collect() };
12417 let val = |s: Scalar| -> Option<f64> {
12418 if s.is_missing() {
12419 None
12420 } else {
12421 s.to_f64().ok()
12422 }
12423 };
12424
12425 assert_eq!(val(nanskew(&f(&[1.0, 2.0]))), None, "skew n=2 -> NaN");
12427 let sym = val(nanskew(&f(&[1.0, 2.0, 3.0]))).expect("skew n=3");
12428 assert!(sym.abs() < 1e-9, "symmetric skew ~0, got {sym}");
12429 let right = val(nanskew(&f(&[1.0, 1.0, 1.0, 5.0]))).expect("skew n=4");
12430 assert!(right > 0.0, "right-skewed -> positive skew, got {right}");
12431
12432 assert_eq!(val(nankurt(&f(&[1.0, 2.0, 3.0]))), None, "kurt n=3 -> NaN");
12434 let k = val(nankurt(&f(&[1.0, 2.0, 3.0, 4.0, 5.0]))).expect("kurt n=5");
12435 assert!(
12436 (k - (-1.2)).abs() < 1e-6,
12437 "pandas kurt([1..5]) == -1.2, got {k}"
12438 );
12439 }
12440
12441 #[test]
12442 #[ignore = "foreground release attribution harness"]
12443 fn nanskew_fused_moment_scan_ab_mavln() {
12444 const ROWS: usize = 100_000;
12445 const BATCH: usize = 8;
12446
12447 fn former(values: &[Scalar]) -> Scalar {
12448 let nums = super::collect_finite(values);
12449 let n = nums.len() as f64;
12450 if n < 3.0 {
12451 return Scalar::Null(NullKind::NaN);
12452 }
12453 let mean = nums.iter().sum::<f64>() / n;
12454 let m2: f64 = nums.iter().map(|x| (x - mean).powi(2)).sum();
12455 let m3: f64 = nums.iter().map(|x| (x - mean).powi(3)).sum();
12456 let s2 = m2 / (n - 1.0);
12457 if s2 == 0.0 {
12458 return Scalar::Float64(0.0);
12459 }
12460 let s3 = s2.powf(1.5);
12461 Scalar::Float64((n / ((n - 1.0) * (n - 2.0))) * (m3 / s3))
12462 }
12463
12464 fn assert_bits_eq(former: Scalar, candidate: Scalar) {
12465 match (former, candidate) {
12466 (Scalar::Float64(a), Scalar::Float64(b)) => assert_eq!(a.to_bits(), b.to_bits()),
12467 (a, b) => assert_eq!(a, b),
12468 }
12469 }
12470
12471 fn elapsed(values: &[Scalar], skew: fn(&[Scalar]) -> Scalar) -> u128 {
12472 std::hint::black_box(skew(std::hint::black_box(values)));
12473 let started = std::time::Instant::now();
12474 for _ in 0..BATCH {
12475 std::hint::black_box(skew(std::hint::black_box(values)));
12476 }
12477 started.elapsed().as_nanos()
12478 }
12479
12480 fn median(samples: &mut [u128]) -> u128 {
12481 samples.sort_unstable();
12482 samples[samples.len() / 2]
12483 }
12484
12485 for values in [
12486 vec![],
12487 vec![Scalar::Int64(1), Scalar::Int64(2)],
12488 vec![Scalar::Int64(7); 16],
12489 vec![
12490 Scalar::Int64(-3),
12491 Scalar::Null(NullKind::NaN),
12492 Scalar::Float64(2.5),
12493 Scalar::Utf8("skip".to_owned()),
12494 Scalar::Int64(11),
12495 ],
12496 ] {
12497 assert_bits_eq(former(&values), super::nanskew(&values));
12498 }
12499
12500 let values = (0..ROWS)
12501 .map(|i| {
12502 if i % 257 == 0 {
12503 Scalar::Null(NullKind::NaN)
12504 } else {
12505 Scalar::Int64(((i * 37 + i / 11) % 10_003) as i64 - 5_001)
12506 }
12507 })
12508 .collect::<Vec<_>>();
12509 assert_bits_eq(former(&values), super::nanskew(&values));
12510
12511 for _ in 0..2 {
12512 std::hint::black_box(elapsed(&values, former));
12513 std::hint::black_box(elapsed(&values, super::nanskew));
12514 }
12515
12516 let mut former_samples = Vec::with_capacity(18);
12517 let mut candidate_samples = Vec::with_capacity(18);
12518 for block in 0_usize..9 {
12519 if block.is_multiple_of(2) {
12520 former_samples.push(elapsed(&values, former));
12521 candidate_samples.push(elapsed(&values, super::nanskew));
12522 candidate_samples.push(elapsed(&values, super::nanskew));
12523 former_samples.push(elapsed(&values, former));
12524 } else {
12525 candidate_samples.push(elapsed(&values, super::nanskew));
12526 former_samples.push(elapsed(&values, former));
12527 former_samples.push(elapsed(&values, former));
12528 candidate_samples.push(elapsed(&values, super::nanskew));
12529 }
12530 }
12531
12532 let former_p50 = median(&mut former_samples);
12533 let candidate_p50 = median(&mut candidate_samples);
12534 eprintln!(
12535 "NANSKEW_FUSED_AB rows={ROWS} batch={BATCH} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} ratio={:.6}",
12536 former_p50 as f64 / candidate_p50 as f64,
12537 );
12538 eprintln!("NANSKEW_FUSED_AB former_samples_ns={former_samples:?}");
12539 eprintln!("NANSKEW_FUSED_AB candidate_samples_ns={candidate_samples:?}");
12540 }
12541
12542 #[test]
12543 #[ignore = "foreground performance probe"]
12544 fn nankurt_fused_moment_scan_ab_idka7() {
12545 const ROWS: usize = 65_536;
12546 const BATCH: usize = 4;
12547
12548 fn former(values: &[Scalar]) -> Scalar {
12549 let nums = super::collect_finite(values);
12550 let n = nums.len() as f64;
12551 if n < 4.0 {
12552 return Scalar::Null(NullKind::NaN);
12553 }
12554 let mean = nums.iter().sum::<f64>() / n;
12555 let m2: f64 = nums.iter().map(|x| (x - mean).powi(2)).sum();
12556 let m4: f64 = nums.iter().map(|x| (x - mean).powi(4)).sum();
12557 let s2 = m2 / (n - 1.0);
12558 if s2 == 0.0 {
12559 return Scalar::Float64(0.0);
12560 }
12561 let adj = (n * (n + 1.0)) / ((n - 1.0) * (n - 2.0) * (n - 3.0));
12562 let sub = (3.0 * (n - 1.0).powi(2)) / ((n - 2.0) * (n - 3.0));
12563 Scalar::Float64(adj * (m4 / (s2 * s2)) - sub)
12564 }
12565
12566 fn assert_bits_eq(former: Scalar, candidate: Scalar) {
12567 match (former, candidate) {
12568 (Scalar::Float64(a), Scalar::Float64(b)) => assert_eq!(a.to_bits(), b.to_bits()),
12569 (a, b) => assert_eq!(a, b),
12570 }
12571 }
12572
12573 fn elapsed(values: &[Scalar], kurt: fn(&[Scalar]) -> Scalar) -> u128 {
12574 let started = std::time::Instant::now();
12575 for _ in 0..BATCH {
12576 std::hint::black_box(kurt(std::hint::black_box(values)));
12577 }
12578 started.elapsed().as_nanos()
12579 }
12580
12581 fn median(samples: &mut [u128]) -> u128 {
12582 samples.sort_unstable();
12583 samples[samples.len() / 2]
12584 }
12585
12586 for values in [
12587 vec![],
12588 vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
12589 vec![Scalar::Int64(7); 16],
12590 vec![
12591 Scalar::Int64(-3),
12592 Scalar::Null(NullKind::NaN),
12593 Scalar::Float64(2.5),
12594 Scalar::Utf8("skip".to_owned()),
12595 Scalar::Int64(11),
12596 Scalar::Float64(-7.25),
12597 ],
12598 ] {
12599 assert_bits_eq(former(&values), super::nankurt(&values));
12600 }
12601
12602 let values = (0..ROWS)
12603 .map(|i| {
12604 if i % 257 == 0 {
12605 Scalar::Null(NullKind::NaN)
12606 } else {
12607 Scalar::Int64(((i * 37 + i / 11) % 10_003) as i64 - 5_001)
12608 }
12609 })
12610 .collect::<Vec<_>>();
12611 assert_bits_eq(former(&values), super::nankurt(&values));
12612
12613 for _ in 0..2 {
12614 std::hint::black_box(elapsed(&values, former));
12615 std::hint::black_box(elapsed(&values, super::nankurt));
12616 }
12617
12618 let mut former_samples = Vec::with_capacity(10);
12619 let mut candidate_samples = Vec::with_capacity(10);
12620 for block in 0_usize..5 {
12621 if block.is_multiple_of(2) {
12622 former_samples.push(elapsed(&values, former));
12623 candidate_samples.push(elapsed(&values, super::nankurt));
12624 candidate_samples.push(elapsed(&values, super::nankurt));
12625 former_samples.push(elapsed(&values, former));
12626 } else {
12627 candidate_samples.push(elapsed(&values, super::nankurt));
12628 former_samples.push(elapsed(&values, former));
12629 former_samples.push(elapsed(&values, former));
12630 candidate_samples.push(elapsed(&values, super::nankurt));
12631 }
12632 }
12633
12634 let former_p50 = median(&mut former_samples);
12635 let candidate_p50 = median(&mut candidate_samples);
12636 eprintln!(
12637 "NANKURT_FUSED_AB rows={ROWS} batch={BATCH} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} ratio={:.6}",
12638 former_p50 as f64 / candidate_p50 as f64,
12639 );
12640 eprintln!("NANKURT_FUSED_AB former_samples_ns={former_samples:?}");
12641 eprintln!("NANKURT_FUSED_AB candidate_samples_ns={candidate_samples:?}");
12642 }
12643
12644 #[test]
12647 fn cast_scalar_to_utf8_formatting_yes7i() {
12648 let mut st: u64 = 0x4e57_0b1c_2d3e_4f50;
12651 let mut next = || {
12652 st = st
12653 .wrapping_mul(6_364_136_223_846_793_005)
12654 .wrapping_add(1_442_695_040_888_963_407);
12655 (st >> 33) as u32
12656 };
12657 for _ in 0..3000u32 {
12658 let n = (next() % 4_000_001) as i64 - 2_000_000;
12659 assert_eq!(
12660 cast_scalar(&Scalar::Int64(n), DType::Utf8).unwrap(),
12661 Scalar::Utf8(n.to_string())
12662 );
12663 }
12664 assert_eq!(
12665 cast_scalar(&Scalar::Bool(true), DType::Utf8).unwrap(),
12666 Scalar::Utf8("True".to_string())
12667 );
12668 assert_eq!(
12669 cast_scalar(&Scalar::Bool(false), DType::Utf8).unwrap(),
12670 Scalar::Utf8("False".to_string())
12671 );
12672 }
12673
12674 #[test]
12675 fn cast_scalar_coercion_rules_6a83t() {
12676 let mut state: u64 = 0x5a17_c0de_1234_abcd;
12677 let mut next = || {
12678 state = state
12679 .wrapping_mul(6_364_136_223_846_793_005)
12680 .wrapping_add(1_442_695_040_888_963_407);
12681 (state >> 33) as u32
12682 };
12683
12684 for _ in 0..4000u32 {
12685 let n = (next() % 21) as i64 - 10; let b = next() % 2 == 0;
12687 let f = f64::from((next() % 41) as i32 - 20) / 4.0; let i = Scalar::Int64(n);
12690 let bo = Scalar::Bool(b);
12691 let fl = Scalar::Float64(f);
12692
12693 assert_eq!(cast_scalar(&i, DType::Int64), Ok(i.clone()));
12695 assert_eq!(cast_scalar(&bo, DType::Bool), Ok(bo.clone()));
12696 assert_eq!(cast_scalar(&fl, DType::Float64), Ok(fl.clone()));
12697
12698 assert_eq!(cast_scalar(&i, DType::Int64Nullable), Ok(i.clone()));
12700 assert_eq!(cast_scalar(&bo, DType::BoolNullable), Ok(bo.clone()));
12701
12702 assert_eq!(cast_scalar(&i, DType::Bool), Ok(Scalar::Bool(n != 0)));
12704 assert_eq!(
12705 cast_scalar(&i, DType::Float64),
12706 Ok(Scalar::Float64(n as f64))
12707 );
12708
12709 assert_eq!(
12711 cast_scalar(&bo, DType::Int64),
12712 Ok(Scalar::Int64(i64::from(b)))
12713 );
12714 assert_eq!(
12715 cast_scalar(&bo, DType::Float64),
12716 Ok(Scalar::Float64(if b { 1.0 } else { 0.0 }))
12717 );
12718
12719 assert_eq!(cast_scalar(&fl, DType::Int64), Ok(Scalar::Int64(f as i64)));
12721 }
12722 }
12723
12724 #[test]
12726 fn scalar_from_primitive_types() {
12727 assert_eq!(Scalar::from(true), Scalar::Bool(true));
12729 assert_eq!(Scalar::from(42i64), Scalar::Int64(42));
12730 assert_eq!(Scalar::from(1.5f64), Scalar::Float64(1.5));
12731 assert_eq!(Scalar::from("hi"), Scalar::Utf8("hi".to_owned()));
12732 assert_eq!(
12733 Scalar::from(String::from("world")),
12734 Scalar::Utf8("world".to_owned())
12735 );
12736
12737 let mixed: Vec<Scalar> = vec![1i64.into(), 2.0f64.into(), "three".into()];
12741 assert_eq!(mixed[0], Scalar::Int64(1));
12742 assert_eq!(mixed[1], Scalar::Float64(2.0));
12743 assert_eq!(mixed[2], Scalar::Utf8("three".to_owned()));
12744 }
12745
12746 #[test]
12747 fn dtype_inference_routes_bool_numeric_mix_to_object_bucket_rh1od() {
12748 let values = vec![Scalar::Bool(true), Scalar::Int64(7), Scalar::Float64(3.5)];
12753 assert_eq!(
12754 infer_dtype(&values).expect("dtype should infer"),
12755 DType::Utf8
12756 );
12757 }
12758
12759 #[test]
12760 fn interval_scalar_has_dtype_storage_and_unique_semantics_5g5uj() {
12761 let left = Scalar::Interval(Interval::new(0.0, 1.0, IntervalClosed::Right));
12762 let right = Scalar::Interval(Interval::new(1.0, 2.0, IntervalClosed::Right));
12763 assert_eq!(left.dtype(), DType::Interval);
12764 assert!(!left.is_missing());
12765 assert_eq!(
12766 infer_dtype(&[left.clone(), right.clone()]).expect("interval dtype"),
12767 DType::Interval
12768 );
12769 assert_eq!(
12770 common_dtype(DType::Interval, DType::Interval).expect("same interval dtype"),
12771 DType::Interval
12772 );
12773 assert_eq!(
12774 cast_scalar(&Scalar::Null(NullKind::Null), DType::Interval).expect("missing casts"),
12775 Scalar::Null(NullKind::Null)
12776 );
12777 assert_eq!(
12778 cast_scalar(&left, DType::Utf8).expect("interval string cast"),
12779 Scalar::Utf8("(0.0, 1.0]".to_owned())
12780 );
12781 assert_eq!(
12782 super::nannunique(&[left.clone(), right, left, Scalar::Null(NullKind::Null)]),
12783 Scalar::Int64(2)
12784 );
12785 }
12786
12787 #[test]
12788 fn cast_scalar_parses_temporal_extension_strings_avm08() {
12789 let expected_nanos = super::Timestamp::parse("2024-01-15T10:30:45")
12790 .expect("timestamp parse")
12791 .nanos;
12792 assert_eq!(
12793 cast_scalar(
12794 &Scalar::Utf8("2024-01-15T10:30:45".to_owned()),
12795 DType::datetime64_naive()
12796 )
12797 .expect("datetime cast"),
12798 Scalar::Datetime64(expected_nanos)
12799 );
12800 assert_eq!(
12801 cast_scalar(&Scalar::Utf8("2024Q1".to_owned()), DType::Period).expect("period cast"),
12802 Scalar::Period(Period::new(216, PeriodFreq::QUARTERLY))
12803 );
12804 assert_eq!(
12805 cast_scalar(&Scalar::Utf8("(0, 1]".to_owned()), DType::Interval)
12806 .expect("interval cast"),
12807 Scalar::Interval(Interval::new(0.0, 1.0, IntervalClosed::Right))
12808 );
12809 }
12810
12811 #[test]
12812 fn missing_values_get_target_missing_marker() {
12813 let missing = Scalar::Null(NullKind::Null);
12814 let cast = cast_scalar(&missing, DType::Float64).expect("missing casts");
12815 assert_eq!(cast, Scalar::Null(NullKind::NaN));
12816 }
12817
12818 #[test]
12819 fn cast_scalar_to_utf8_uses_pandas_string_spellings() {
12820 let cases = [
12821 (Scalar::Bool(true), "True"),
12822 (Scalar::Bool(false), "False"),
12823 (Scalar::Int64(-7), "-7"),
12824 (Scalar::Float64(1.0), "1.0"),
12825 (Scalar::Float64(1.5), "1.5"),
12826 (Scalar::Float64(f64::NAN), "nan"),
12827 (Scalar::Null(NullKind::Null), "None"),
12828 (Scalar::Null(NullKind::NaN), "nan"),
12829 (Scalar::Null(NullKind::NaT), "NaT"),
12830 ];
12831
12832 for (value, expected) in cases {
12833 assert_eq!(
12834 cast_scalar(&value, DType::Utf8).expect("cast"),
12835 Scalar::Utf8(expected.to_owned())
12836 );
12837 }
12838 }
12839
12840 #[test]
12841 fn semantic_eq_treats_nan_as_equal() {
12842 let left = Scalar::Float64(f64::NAN);
12843 let right = Scalar::Null(NullKind::NaN);
12844 assert!(left.semantic_eq(&right));
12845 }
12846
12847 #[test]
12848 fn semantic_eq_treats_nan_as_missing_null() {
12849 let left = Scalar::Float64(f64::NAN);
12850 let right = Scalar::Null(NullKind::Null);
12851 assert!(left.semantic_eq(&right));
12852 }
12853
12854 #[test]
12873 fn semantic_eq_unifies_dtype_sentinel_missing_with_null_xwxci() {
12874 for sentinel in [
12875 Scalar::Timedelta64(Timedelta::NAT),
12876 Scalar::Datetime64(Timestamp::NAT),
12877 Scalar::Period(Period::new(i64::MIN, PeriodFreq::Daily)),
12878 ] {
12879 assert!(sentinel.is_missing(), "{sentinel:?} must report missing");
12880 for marker in [
12881 Scalar::Null(NullKind::Null),
12882 Scalar::Null(NullKind::NaN),
12883 Scalar::Null(NullKind::NaT),
12884 ] {
12885 assert!(
12886 sentinel.semantic_eq(&marker),
12887 "{sentinel:?} vs {marker:?} are both missing"
12888 );
12889 assert!(marker.semantic_eq(&sentinel), "and symmetrically");
12890 }
12891 }
12892
12893 let present = Scalar::Timedelta64(-60);
12895 assert!(!Scalar::Timedelta64(Timedelta::NAT).semantic_eq(&present));
12896 assert!(!present.semantic_eq(&Scalar::Null(NullKind::Null)));
12897 assert!(!present.semantic_eq(&Scalar::Timedelta64(-61)));
12899 }
12900
12901 #[test]
12902 fn common_dtype_rejects_string_numeric_mix() {
12903 let err = common_dtype(DType::Utf8, DType::Int64).expect_err("must fail");
12904 assert_eq!(
12905 err.to_string(),
12906 "dtype coercion from Utf8 to Int64 has no compatible common type"
12907 );
12908 let err = common_dtype(DType::Float64, DType::Utf8).expect_err("must fail");
12909 assert_eq!(
12910 err.to_string(),
12911 "dtype coercion from Float64 to Utf8 has no compatible common type"
12912 );
12913 }
12914
12915 #[test]
12916 fn sparse_dtype_normalizes_fill_value_to_value_dtype() {
12917 let dtype = SparseDType::new(DType::Float64, Scalar::Int64(0)).expect("fill should cast");
12918
12919 assert_eq!(dtype.value_dtype, DType::Float64);
12920 assert_eq!(dtype.fill_value, Scalar::Float64(0.0));
12921 }
12922
12923 #[test]
12924 fn sparse_dtype_rejects_sparse_value_dtype() {
12925 let err = SparseDType::new(DType::Sparse, Scalar::Int64(0)).expect_err("must reject");
12926
12927 assert_eq!(err.to_string(), "sparse value dtype cannot be Sparse");
12928 }
12929
12930 #[test]
12931 fn common_dtype_rejects_sparse_dense_mix() {
12932 let err = common_dtype(DType::Sparse, DType::Int64).expect_err("must fail");
12933
12934 assert_eq!(
12935 err.to_string(),
12936 "dtype coercion from Sparse to Int64 has no compatible common type"
12937 );
12938 }
12939
12940 #[test]
12943 fn nullable_int64_promotion_matrix() {
12944 assert_eq!(
12946 common_dtype(DType::Int64, DType::Int64Nullable).unwrap(),
12947 DType::Int64Nullable
12948 );
12949 assert_eq!(
12950 common_dtype(DType::Int64Nullable, DType::Int64).unwrap(),
12951 DType::Int64Nullable
12952 );
12953
12954 assert_eq!(
12961 common_dtype(DType::Int64Nullable, DType::Float64).unwrap(),
12962 DType::Float64Nullable
12963 );
12964 assert_eq!(
12965 common_dtype(DType::Float64, DType::Int64Nullable).unwrap(),
12966 DType::Float64Nullable
12967 );
12968
12969 assert_eq!(
12971 common_dtype(DType::Int64Nullable, DType::Int64Nullable).unwrap(),
12972 DType::Int64Nullable
12973 );
12974
12975 assert_eq!(
12977 common_dtype(DType::Bool, DType::Int64Nullable).unwrap(),
12978 DType::Int64Nullable
12979 );
12980
12981 assert_eq!(
12983 common_dtype(DType::BoolNullable, DType::Int64).unwrap(),
12984 DType::Int64Nullable
12985 );
12986 }
12987
12988 #[test]
12989 fn nullable_bool_promotion_matrix() {
12990 assert_eq!(
12992 common_dtype(DType::Bool, DType::BoolNullable).unwrap(),
12993 DType::BoolNullable
12994 );
12995 assert_eq!(
12996 common_dtype(DType::BoolNullable, DType::Bool).unwrap(),
12997 DType::BoolNullable
12998 );
12999
13000 assert_eq!(
13007 common_dtype(DType::BoolNullable, DType::Float64).unwrap(),
13008 DType::Float64Nullable
13009 );
13010
13011 assert_eq!(
13014 common_dtype(DType::Bool, DType::Float64).unwrap(),
13015 DType::Float64
13016 );
13017 }
13018
13019 #[test]
13020 fn dtype_is_nullable_helper() {
13021 assert!(DType::Int64Nullable.is_nullable());
13022 assert!(DType::BoolNullable.is_nullable());
13023 assert!(!DType::Int64.is_nullable());
13024 assert!(!DType::Bool.is_nullable());
13025 assert!(!DType::Float64.is_nullable());
13026 assert!(!DType::Utf8.is_nullable());
13027 }
13028
13029 #[test]
13030 fn dtype_to_nullable_conversions() {
13031 assert_eq!(DType::Int64.to_nullable(), DType::Int64Nullable);
13032 assert_eq!(DType::Bool.to_nullable(), DType::BoolNullable);
13033 assert_eq!(DType::Float64.to_nullable(), DType::Float64Nullable);
13043 assert_eq!(
13044 DType::Float64Nullable.to_nullable(),
13045 DType::Float64Nullable,
13046 "idempotent: already nullable"
13047 );
13048 assert_eq!(DType::Int64Nullable.to_nullable(), DType::Int64Nullable);
13049 }
13050
13051 #[test]
13052 fn dtype_to_non_nullable_conversions() {
13053 assert_eq!(DType::Int64Nullable.to_non_nullable(), DType::Int64);
13054 assert_eq!(DType::BoolNullable.to_non_nullable(), DType::Bool);
13055 assert_eq!(DType::Int64.to_non_nullable(), DType::Int64); assert_eq!(DType::Float64.to_non_nullable(), DType::Float64);
13057 }
13058
13059 #[test]
13060 fn nullable_dtype_name_reports_pandas_style() {
13061 assert_eq!(DType::Int64.name(), "int64");
13062 assert_eq!(DType::Int64Nullable.name(), "Int64"); assert_eq!(DType::Bool.name(), "bool");
13064 assert_eq!(DType::BoolNullable.name(), "boolean");
13065 }
13066
13067 #[test]
13068 fn cast_scalar_int64_nullable_identity() {
13069 let val = Scalar::Int64(42);
13070 let result = cast_scalar(&val, DType::Int64Nullable).unwrap();
13072 assert_eq!(result, Scalar::Int64(42));
13073
13074 let result2 = cast_scalar(&val, DType::Int64).unwrap();
13076 assert_eq!(result2, Scalar::Int64(42));
13077 }
13078
13079 #[test]
13080 fn cast_float_to_utf8_uses_pandas_str_float_with_scientific() {
13081 let cases: &[(f64, &str)] = &[
13086 (1.0, "1.0"),
13087 (2.5, "2.5"),
13088 (100.0, "100.0"),
13089 (0.1, "0.1"),
13090 (0.0001, "0.0001"),
13091 (1e16, "1e+16"),
13092 (1e20, "1e+20"),
13093 (1e-5, "1e-05"),
13094 (1e-7, "1e-07"),
13095 (f64::INFINITY, "inf"),
13096 (f64::NEG_INFINITY, "-inf"),
13097 ];
13098 for (v, expected) in cases {
13099 assert_eq!(
13100 cast_scalar(&Scalar::Float64(*v), DType::Utf8).unwrap(),
13101 Scalar::Utf8((*expected).to_owned()),
13102 "float {v} -> str"
13103 );
13104 }
13105 }
13106
13107 fn float_to_string_for_astype_former(value: f64) -> String {
13108 if value.is_nan() {
13109 return "nan".to_owned();
13110 }
13111 if value.is_infinite() {
13112 return value.to_string();
13113 }
13114 let rendered = format!("{value:?}");
13115 match rendered.split_once('e') {
13116 None => rendered,
13117 Some((mantissa, exponent)) => {
13118 let (sign, digits) = match exponent.strip_prefix('-') {
13119 Some(digits) => ('-', digits),
13120 None => ('+', exponent.strip_prefix('+').unwrap_or(exponent)),
13121 };
13122 format!("{mantissa}e{sign}{digits:0>2}")
13123 }
13124 }
13125 }
13126
13127 fn scientific_astype_values(len: usize) -> Vec<f64> {
13128 const EXPONENTS: [i32; 16] = [
13129 -300, -200, -100, -50, -10, -7, -6, -5, 16, 17, 20, 50, 100, 200, 300, 307,
13130 ];
13131 (0..len)
13132 .map(|position| {
13133 let mantissa = 1.0 + (position % 997) as f64 / 997.0;
13134 let magnitude = mantissa * 10.0_f64.powi(EXPONENTS[position % EXPONENTS.len()]);
13135 if position.is_multiple_of(2) {
13136 magnitude
13137 } else {
13138 -magnitude
13139 }
13140 })
13141 .collect()
13142 }
13143
13144 #[test]
13145 fn float_to_string_for_astype_in_place_matches_former() {
13146 let fixed = [
13147 f64::NAN,
13148 f64::INFINITY,
13149 f64::NEG_INFINITY,
13150 0.0,
13151 -0.0,
13152 f64::MIN_POSITIVE,
13153 f64::MAX,
13154 f64::MIN,
13155 1e16,
13156 -1e16,
13157 1e-5,
13158 -1e-5,
13159 1.234_567_890_123_456_8e20,
13160 -9.876_543_210_987_654e-123,
13161 ];
13162 for value in fixed.into_iter().chain(scientific_astype_values(16_384)) {
13163 assert_eq!(
13164 super::float_to_string_for_astype(value),
13165 float_to_string_for_astype_former(value),
13166 "value={value:?}"
13167 );
13168 }
13169 }
13170
13171 #[test]
13172 #[ignore = "foreground performance probe"]
13173 fn float_to_string_for_astype_in_place_ab() {
13174 use std::time::Instant;
13175
13176 const VALUES: usize = 16_384;
13177 const SAMPLES: usize = 10;
13178 let values = scientific_astype_values(VALUES);
13179 for &value in &values {
13180 let former = float_to_string_for_astype_former(value);
13181 assert!(former.contains('e'), "benchmark value must be scientific");
13182 assert_eq!(super::float_to_string_for_astype(value), former);
13183 }
13184
13185 for _ in 0..2 {
13186 for &value in &values {
13187 std::hint::black_box(float_to_string_for_astype_former(value));
13188 std::hint::black_box(super::float_to_string_for_astype(value));
13189 }
13190 }
13191
13192 let mut former_ns = Vec::with_capacity(SAMPLES);
13193 let mut public_ns = Vec::with_capacity(SAMPLES);
13194 for sample in 0..SAMPLES {
13195 let run = |formatter: fn(f64) -> String| {
13196 let started = Instant::now();
13197 for &value in std::hint::black_box(&values) {
13198 std::hint::black_box(formatter(std::hint::black_box(value)));
13199 }
13200 started.elapsed().as_nanos()
13201 };
13202 if sample.is_multiple_of(2) {
13203 former_ns.push(run(float_to_string_for_astype_former));
13204 public_ns.push(run(super::float_to_string_for_astype));
13205 } else {
13206 public_ns.push(run(super::float_to_string_for_astype));
13207 former_ns.push(run(float_to_string_for_astype_former));
13208 }
13209 }
13210
13211 former_ns.sort_unstable();
13212 public_ns.sort_unstable();
13213 let former_p50 = former_ns[SAMPLES / 2];
13214 let public_p50 = public_ns[SAMPLES / 2];
13215 println!(
13216 "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:?}",
13217 former_p50 as f64 / public_p50 as f64
13218 );
13219 }
13220
13221 #[test]
13222 fn cast_float_to_utf8_threshold_boundaries_match_python() {
13223 let cases: &[(f64, &str)] = &[
13228 (1e15, "1000000000000000.0"),
13229 (9_999_999_999_999_998.0, "9999999999999998.0"),
13230 (1_234_567_890_123_456.0, "1234567890123456.0"),
13231 (123_456_789_012_345.0, "123456789012345.0"),
13232 (12_345_678_901_234_567.0, "1.2345678901234568e+16"),
13233 (1e16, "1e+16"),
13234 (1.5e16, "1.5e+16"),
13235 (1e17, "1e+17"),
13236 (1e-4, "0.0001"),
13237 (5e-5, "5e-05"),
13238 (-1e15, "-1000000000000000.0"),
13239 (-1e16, "-1e+16"),
13240 (-1e-5, "-1e-05"),
13241 ];
13242 for (v, expected) in cases {
13243 assert_eq!(
13244 cast_scalar(&Scalar::Float64(*v), DType::Utf8).unwrap(),
13245 Scalar::Utf8((*expected).to_owned()),
13246 "float {v} -> str"
13247 );
13248 }
13249 }
13250
13251 #[test]
13252 fn cast_to_bool_uses_pandas_nonzero_truthiness() {
13253 let cases_int: &[(i64, bool)] = &[(0, false), (1, true), (-3, true), (2, true)];
13257 for (v, expected) in cases_int {
13258 assert_eq!(
13259 cast_scalar(&Scalar::Int64(*v), DType::Bool).unwrap(),
13260 Scalar::Bool(*expected),
13261 "int {v} -> bool"
13262 );
13263 }
13264 let cases_float: &[(f64, bool)] = &[
13265 (0.0, false),
13266 (-0.0, false),
13267 (0.1, true),
13268 (2.5, true),
13269 (1.0, true),
13270 (f64::NAN, true),
13272 ];
13273 for (v, expected) in cases_float {
13274 assert_eq!(
13275 cast_scalar(&Scalar::Float64(*v), DType::Bool).unwrap(),
13276 Scalar::Bool(*expected),
13277 "float {v} -> bool"
13278 );
13279 }
13280 }
13281
13282 #[test]
13283 fn nullable_dtype_is_extension() {
13284 assert!(DType::Int64Nullable.is_extension());
13285 assert!(DType::BoolNullable.is_extension());
13286 assert!(!DType::Int64.is_extension());
13287 assert!(!DType::Bool.is_extension());
13288 }
13289
13290 #[test]
13291 fn infer_dtype_preserves_string_numeric_mix_as_utf8_bucket() {
13292 let values = vec![Scalar::Utf8("x".into()), Scalar::Int64(7)];
13293 assert_eq!(
13294 infer_dtype(&values).expect("dtype should infer"),
13295 DType::Utf8
13296 );
13297 }
13298
13299 #[test]
13300 fn infer_dtype_routes_bool_numeric_mix_to_utf8_object_bucket_rh1od() {
13301 let values = vec![Scalar::Bool(true), Scalar::Int64(7), Scalar::Bool(false)];
13307 assert_eq!(
13308 infer_dtype(&values).expect("dtype should infer"),
13309 DType::Utf8
13310 );
13311 let with_float = vec![Scalar::Int64(1), Scalar::Float64(2.5), Scalar::Bool(true)];
13312 assert_eq!(
13313 infer_dtype(&with_float).expect("dtype should infer"),
13314 DType::Utf8
13315 );
13316 let with_null = vec![
13317 Scalar::Bool(true),
13318 Scalar::Null(NullKind::Null),
13319 Scalar::Int64(2),
13320 ];
13321 assert_eq!(
13322 infer_dtype(&with_null).expect("dtype should infer"),
13323 DType::Utf8
13324 );
13325 }
13326
13327 #[test]
13328 fn infer_dtype_keeps_nonmixed_bool_and_numeric_paths_rh1od() {
13329 assert_eq!(
13333 infer_dtype(&[Scalar::Bool(true), Scalar::Bool(false)]).expect("dtype should infer"),
13334 DType::Bool
13335 );
13336 assert_eq!(
13337 infer_dtype(&[Scalar::Int64(1), Scalar::Float64(2.5)]).expect("dtype should infer"),
13338 DType::Float64
13339 );
13340 }
13341
13342 #[test]
13345 fn is_null_detects_explicit_nulls() {
13346 assert!(Scalar::Null(NullKind::Null).is_null());
13347 assert!(Scalar::Null(NullKind::NaN).is_null());
13348 assert!(!Scalar::Int64(42).is_null());
13349 assert!(!Scalar::Float64(f64::NAN).is_null());
13350 }
13351
13352 #[test]
13353 fn is_na_matches_is_missing() {
13354 let vals = vec![
13355 Scalar::Null(NullKind::Null),
13356 Scalar::Float64(f64::NAN),
13357 Scalar::Int64(0),
13358 Scalar::Bool(false),
13359 ];
13360 for v in &vals {
13361 assert_eq!(v.is_na(), v.is_missing());
13362 }
13363 }
13364
13365 #[test]
13366 fn coalesce_picks_first_non_missing() {
13367 let null = Scalar::Null(NullKind::Null);
13368 let fill = Scalar::Int64(99);
13369 assert_eq!(null.coalesce(&fill), fill);
13370 assert_eq!(fill.coalesce(&null), fill);
13371 }
13372
13373 #[test]
13376 fn isna_notna_complement() {
13377 let vals = vec![
13378 Scalar::Int64(1),
13379 Scalar::Null(NullKind::Null),
13380 Scalar::Float64(f64::NAN),
13381 Scalar::Float64(3.0),
13382 ];
13383 let na = super::isna(&vals);
13384 let not = super::notna(&vals);
13385 assert_eq!(na, vec![false, true, true, false]);
13386 for (a, b) in na.iter().zip(not.iter()) {
13387 assert_ne!(a, b);
13388 }
13389 }
13390
13391 #[test]
13392 fn count_na_counts_missing() {
13393 let vals = vec![
13394 Scalar::Int64(1),
13395 Scalar::Null(NullKind::Null),
13396 Scalar::Float64(f64::NAN),
13397 ];
13398 assert_eq!(super::count_na(&vals), 2);
13399 }
13400
13401 #[test]
13402 fn fill_na_replaces_missing() {
13403 let vals = vec![
13404 Scalar::Int64(1),
13405 Scalar::Null(NullKind::Null),
13406 Scalar::Float64(f64::NAN),
13407 Scalar::Int64(4),
13408 ];
13409 let filled = super::fill_na(&vals, &Scalar::Int64(0));
13410 assert_eq!(filled[0], Scalar::Int64(1));
13411 assert_eq!(filled[1], Scalar::Int64(0));
13412 assert_eq!(filled[2], Scalar::Int64(0));
13413 assert_eq!(filled[3], Scalar::Int64(4));
13414 }
13415
13416 #[test]
13417 fn dropna_removes_missing() {
13418 let vals = vec![
13419 Scalar::Int64(1),
13420 Scalar::Null(NullKind::Null),
13421 Scalar::Int64(3),
13422 Scalar::Float64(f64::NAN),
13423 ];
13424 let kept = super::dropna(&vals);
13425 assert_eq!(kept.len(), 2);
13426 assert_eq!(kept[0], Scalar::Int64(1));
13427 assert_eq!(kept[1], Scalar::Int64(3));
13428 }
13429
13430 #[test]
13431 fn null_helpers_match_scalar_oracle_imt0c() {
13432 fn next(seed: &mut u64) -> u64 {
13435 *seed = seed
13436 .wrapping_mul(3202034522624059733)
13437 .wrapping_add(4354685564936845319);
13438 *seed
13439 }
13440
13441 fn assert_null_helpers(case: usize, values: &[Scalar], fill: &Scalar) {
13442 let expected_missing = values.iter().filter(|value| value.is_missing()).count();
13443 let expected_dropped = values
13444 .iter()
13445 .filter(|value| !value.is_missing())
13446 .cloned()
13447 .collect::<Vec<_>>();
13448 let expected_filled = values
13449 .iter()
13450 .map(|value| {
13451 if value.is_missing() {
13452 fill.clone()
13453 } else {
13454 value.clone()
13455 }
13456 })
13457 .collect::<Vec<_>>();
13458
13459 assert_eq!(
13460 super::count_na(values),
13461 expected_missing,
13462 "case={case}: count_na mismatch for {values:?}"
13463 );
13464
13465 let dropped = super::dropna(values);
13466 assert_eq!(
13467 dropped.len(),
13468 expected_dropped.len(),
13469 "case={case}: dropna length mismatch for {values:?}"
13470 );
13471 for (pos, (actual, expected)) in dropped.iter().zip(expected_dropped.iter()).enumerate()
13472 {
13473 assert!(
13474 actual.semantic_eq(expected),
13475 "case={case} pos={pos}: dropna expected {expected:?}, got {actual:?}"
13476 );
13477 }
13478
13479 let filled = super::fill_na(values, fill);
13480 assert_eq!(
13481 filled.len(),
13482 expected_filled.len(),
13483 "case={case}: fill_na length mismatch for {values:?}"
13484 );
13485 for (pos, (actual, expected)) in filled.iter().zip(expected_filled.iter()).enumerate() {
13486 assert!(
13487 actual.semantic_eq(expected),
13488 "case={case} pos={pos}: fill_na expected {expected:?}, got {actual:?}"
13489 );
13490 }
13491 }
13492
13493 let all_missing = [
13494 Scalar::Null(NullKind::Null),
13495 Scalar::Null(NullKind::NaN),
13496 Scalar::Float64(f64::NAN),
13497 Scalar::Timedelta64(i64::MIN),
13498 ];
13499 assert_null_helpers(usize::MAX, &all_missing, &Scalar::Utf8("filled".into()));
13500
13501 let mut seed = 0xc011_a7ed_0b5e_1a55_u64;
13502 for case in 0..260 {
13503 let len = (next(&mut seed) % 83 + 1) as usize;
13504 let mut values = Vec::with_capacity(len);
13505 for pos in 0..len {
13506 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
13507 values.push(match next(&mut seed) % 11 {
13508 0 => Scalar::Null(NullKind::Null),
13509 1 => Scalar::Null(NullKind::NaN),
13510 2 => Scalar::Float64(f64::NAN),
13511 3 => Scalar::Timedelta64(i64::MIN),
13512 4 => Scalar::Bool(raw & 1 == 0),
13513 5 => Scalar::Int64(raw),
13514 6 => Scalar::Float64(raw as f64 / 37.0),
13515 7 => Scalar::Float64(if raw & 1 == 0 { 0.0 } else { -0.0 }),
13516 8 => Scalar::Utf8(format!("null_helper_{case}_{pos}")),
13517 9 => Scalar::Utf8(String::new()),
13518 _ => Scalar::Timedelta64(raw),
13519 });
13520 }
13521
13522 let fill = match case % 5 {
13523 0 => Scalar::Bool(true),
13524 1 => Scalar::Int64(-777),
13525 2 => Scalar::Float64(12.5),
13526 3 => Scalar::Utf8("filled".into()),
13527 _ => Scalar::Timedelta64(123_456),
13528 };
13529 assert_null_helpers(case, &values, &fill);
13530 }
13531 }
13532
13533 #[test]
13536 fn nansum_skips_nulls() {
13537 let vals = vec![
13538 Scalar::Float64(1.0),
13539 Scalar::Null(NullKind::Null),
13540 Scalar::Float64(2.0),
13541 Scalar::Float64(f64::NAN),
13542 Scalar::Int64(7),
13543 ];
13544 assert_eq!(super::nansum(&vals), Scalar::Float64(10.0));
13545 }
13546
13547 #[test]
13548 fn nansum_empty_returns_zero() {
13549 assert_eq!(super::nansum(&[]), Scalar::Float64(0.0));
13550 }
13551
13552 #[test]
13553 fn nansum_nanmean_match_numeric_and_timedelta_oracle_1xmi7() {
13554 fn next(seed: &mut u64) -> u64 {
13557 *seed = seed
13558 .wrapping_mul(6364136223846793005)
13559 .wrapping_add(1442695040888963407);
13560 *seed
13561 }
13562
13563 fn expected_numeric(values: &[Scalar]) -> (Scalar, Scalar) {
13564 let mut sum = 0.0;
13565 let mut count = 0usize;
13566 for value in values {
13567 if value.is_missing() {
13568 continue;
13569 }
13570 if let Ok(value) = value.to_f64() {
13571 sum += value;
13572 count += 1;
13573 }
13574 }
13575 let mean = if count == 0 {
13576 Scalar::Null(NullKind::NaN)
13577 } else {
13578 Scalar::Float64(sum / count as f64)
13579 };
13580 (Scalar::Float64(sum), mean)
13581 }
13582
13583 fn expected_timedelta(values: &[Scalar]) -> (Scalar, Scalar) {
13584 let mut sum = 0_i128;
13585 let mut count = 0_i128;
13586 for value in values {
13587 if let Scalar::Timedelta64(ns) = value
13588 && !value.is_missing()
13589 {
13590 sum += i128::from(*ns);
13591 count += 1;
13592 }
13593 }
13594 if count == 0 {
13595 return (Scalar::Timedelta64(0), Scalar::Timedelta64(Timedelta::NAT));
13596 }
13597 (
13603 super::timedelta_ns_to_scalar(sum),
13604 super::timedelta_ns_to_scalar(sum / count),
13605 )
13606 }
13607
13608 fn assert_sum_mean(
13609 case: usize,
13610 family: &str,
13611 values: &[Scalar],
13612 expected_sum: Scalar,
13613 expected_mean: Scalar,
13614 ) {
13615 let actual_sum = super::nansum(values);
13616 let actual_mean = super::nanmean(values);
13617 assert!(
13618 actual_sum.semantic_eq(&expected_sum),
13619 "case={case} family={family}: expected sum {expected_sum:?}, got {actual_sum:?} for {values:?}"
13620 );
13621 assert!(
13622 actual_mean.semantic_eq(&expected_mean),
13623 "case={case} family={family}: expected mean {expected_mean:?}, got {actual_mean:?} for {values:?}"
13624 );
13625 }
13626
13627 let all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
13628 let (sum, mean) = expected_numeric(&all_missing);
13629 assert_sum_mean(usize::MAX, "numeric_all_missing", &all_missing, sum, mean);
13630
13631 let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
13632 let (sum, mean) = expected_timedelta(&td_all_missing);
13633 assert_sum_mean(
13634 usize::MAX - 1,
13635 "timedelta_all_missing",
13636 &td_all_missing,
13637 sum,
13638 mean,
13639 );
13640
13641 let mut seed = 0x511d_ed5a_7a11_1a55_u64;
13642 for case in 0..260 {
13643 let len = (next(&mut seed) % 89 + 1) as usize;
13644
13645 let mut numeric = Vec::with_capacity(len);
13646 numeric.push(Scalar::Int64(case as i64 - 130));
13647 for _ in 1..len {
13648 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
13649 numeric.push(match next(&mut seed) % 8 {
13650 0 => Scalar::Null(NullKind::Null),
13651 1 => Scalar::Null(NullKind::NaN),
13652 2 => Scalar::Float64(f64::NAN),
13653 3 => Scalar::Bool(raw & 1 == 0),
13654 4 => Scalar::Int64(raw % 257),
13655 5 => Scalar::Float64(raw as f64 / 67.0),
13656 6 => Scalar::Float64(0.0),
13657 _ => Scalar::Float64(-0.0),
13658 });
13659 }
13660 let (sum, mean) = expected_numeric(&numeric);
13661 assert_sum_mean(case, "numeric", &numeric, sum, mean);
13662
13663 let mut timedeltas = Vec::with_capacity(len);
13664 timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
13665 for _ in 1..len {
13666 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
13667 timedeltas.push(match next(&mut seed) % 7 {
13668 0 => Scalar::Null(NullKind::Null),
13669 1 => Scalar::Timedelta64(i64::MIN),
13670 _ => Scalar::Timedelta64(raw),
13671 });
13672 }
13673 let (sum, mean) = expected_timedelta(&timedeltas);
13674 assert_sum_mean(case, "timedelta", &timedeltas, sum, mean);
13675 }
13676 }
13677
13678 #[test]
13679 fn nannunique_merges_negative_zero_and_zero() {
13680 let vals = vec![
13681 Scalar::Float64(-0.0),
13682 Scalar::Float64(0.0),
13683 Scalar::Float64(1.0),
13684 ];
13685 assert_eq!(super::nannunique(&vals), Scalar::Int64(2));
13686 }
13687
13688 #[test]
13689 fn nannunique_matches_scalar_bucket_oracle_elvbg() {
13690 fn next(seed: &mut u64) -> u64 {
13693 *seed = seed
13694 .wrapping_mul(2862933555777941757)
13695 .wrapping_add(3037000493);
13696 *seed
13697 }
13698
13699 fn same_bucket(left: &Scalar, right: &Scalar) -> bool {
13700 match (left, right) {
13701 (Scalar::Float64(left), Scalar::Float64(right)) => {
13702 let left = if *left == 0.0 { 0.0 } else { *left };
13703 let right = if *right == 0.0 { 0.0 } else { *right };
13704 left.to_bits() == right.to_bits()
13705 }
13706 _ => left == right,
13707 }
13708 }
13709
13710 fn expected_nunique(values: &[Scalar]) -> i64 {
13711 let mut seen = Vec::<Scalar>::new();
13712 for value in values {
13713 if value.is_missing() {
13714 continue;
13715 }
13716 if !seen.iter().any(|existing| same_bucket(existing, value)) {
13717 seen.push(value.clone());
13718 }
13719 }
13720 seen.len() as i64
13721 }
13722
13723 fn assert_nannunique(case: usize, values: &[Scalar]) {
13724 assert_eq!(
13725 super::nannunique(values),
13726 Scalar::Int64(expected_nunique(values)),
13727 "case={case}: nannunique mismatch for {values:?}"
13728 );
13729 }
13730
13731 assert_nannunique(
13732 usize::MAX,
13733 &[
13734 Scalar::Float64(-0.0),
13735 Scalar::Float64(0.0),
13736 Scalar::Float64(f64::NAN),
13737 Scalar::Null(NullKind::Null),
13738 Scalar::Timedelta64(i64::MIN),
13739 ],
13740 );
13741
13742 let mut seed = 0x0e1b_60d0_b5e7_u64;
13743 for case in 0..320 {
13744 let len = (next(&mut seed) % 97 + 1) as usize;
13745 let mut values = Vec::with_capacity(len);
13746 for pos in 0..len {
13747 let raw = (next(&mut seed) % 1_001) as i64 - 500;
13748 values.push(match next(&mut seed) % 11 {
13749 0 => Scalar::Null(NullKind::Null),
13750 1 => Scalar::Null(NullKind::NaN),
13751 2 => Scalar::Float64(f64::NAN),
13752 3 => Scalar::Bool(raw & 1 == 0),
13753 4 => Scalar::Int64(raw % 37),
13754 5 => Scalar::Float64(raw as f64 / 19.0),
13755 6 => Scalar::Float64(0.0),
13756 7 => Scalar::Float64(-0.0),
13757 8 => Scalar::Utf8(format!("uniq_{}", pos % 13)),
13758 9 => Scalar::Utf8(String::new()),
13759 _ => Scalar::Timedelta64(raw % 41),
13760 });
13761 }
13762 assert_nannunique(case, &values);
13763 }
13764 }
13765
13766 #[test]
13767 fn nanmean_basic() {
13768 let vals = vec![
13769 Scalar::Float64(2.0),
13770 Scalar::Null(NullKind::Null),
13771 Scalar::Float64(4.0),
13772 ];
13773 assert_eq!(super::nanmean(&vals), Scalar::Float64(3.0));
13774 }
13775
13776 #[test]
13777 fn nanmean_all_null_returns_nan() {
13778 let vals = vec![Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
13779 assert!(super::nanmean(&vals).is_missing());
13780 }
13781
13782 #[test]
13783 fn nansum_nanmean_timedelta64_preserves_dtype_620mj() {
13784 let one_hour = 3_600 * 1_000_000_000_i64;
13788 let vals = vec![
13789 Scalar::Timedelta64(one_hour),
13790 Scalar::Timedelta64(2 * one_hour),
13791 Scalar::Timedelta64(3 * one_hour),
13792 ];
13793 assert_eq!(super::nansum(&vals), Scalar::Timedelta64(6 * one_hour));
13794 assert_eq!(super::nanmean(&vals), Scalar::Timedelta64(2 * one_hour));
13795 }
13796
13797 #[test]
13798 fn nansum_nanmean_timedelta64_skips_nat_620mj() {
13799 let one_hour = 3_600 * 1_000_000_000_i64;
13800 let vals = vec![
13801 Scalar::Timedelta64(Timedelta::NAT),
13802 Scalar::Timedelta64(one_hour),
13803 Scalar::Timedelta64(3 * one_hour),
13804 Scalar::Timedelta64(Timedelta::NAT),
13805 ];
13806 assert_eq!(super::nansum(&vals), Scalar::Timedelta64(4 * one_hour));
13808 assert_eq!(super::nanmean(&vals), Scalar::Timedelta64(2 * one_hour));
13809 }
13810
13811 #[test]
13818 fn nansum_timedelta_overflow_is_nat_not_fabricated_max_opz27() {
13819 let vals = vec![Scalar::Timedelta64(i64::MAX), Scalar::Timedelta64(i64::MAX)];
13820 let got = super::nansum(&vals);
13821 assert!(
13822 got.is_missing(),
13823 "overflowing sum must be missing, got {got:?}"
13824 );
13825 assert_eq!(got, Scalar::Timedelta64(Timedelta::NAT));
13826 assert_ne!(got, Scalar::Timedelta64(i64::MAX));
13827 }
13828
13829 #[test]
13834 fn nansum_timedelta_negative_overflow_is_nat_opz27() {
13835 let min_repr = i64::MIN + 1; let vals = vec![Scalar::Timedelta64(min_repr), Scalar::Timedelta64(min_repr)];
13837 assert_eq!(super::nansum(&vals), Scalar::Timedelta64(Timedelta::NAT));
13838
13839 let exact = vec![Scalar::Timedelta64(min_repr + 1), Scalar::Timedelta64(-1)];
13842 let got = super::nansum(&exact);
13843 assert_eq!(got, Scalar::Timedelta64(min_repr));
13844 assert!(!got.is_missing(), "Timedelta.min is representable, not NaT");
13845 }
13846
13847 #[test]
13851 fn nanptp_timedelta_overflow_is_nat_opz27() {
13852 let vals = vec![
13853 Scalar::Timedelta64(i64::MIN + 1),
13854 Scalar::Timedelta64(i64::MAX),
13855 ];
13856 let got = super::nanptp(&vals);
13857 assert!(
13858 got.is_missing(),
13859 "unrepresentable range must be NaT, got {got:?}"
13860 );
13861 assert_ne!(got, Scalar::Timedelta64(i64::MAX));
13862
13863 let hour = 3_600 * 1_000_000_000_i64;
13866 let ok = vec![Scalar::Timedelta64(hour), Scalar::Timedelta64(4 * hour)];
13867 assert_eq!(super::nanptp(&ok), Scalar::Timedelta64(3 * hour));
13868 }
13869
13870 #[test]
13875 fn nancumsum_timedelta_overflow_recovers_exact_value_opz27() {
13876 let vals = vec![
13877 Scalar::Timedelta64(i64::MAX),
13878 Scalar::Timedelta64(i64::MAX), Scalar::Timedelta64(i64::MIN + 1), ];
13881 let out = super::nancumsum(&vals);
13882 assert_eq!(out.len(), 3);
13883 assert_eq!(out[0], Scalar::Timedelta64(i64::MAX));
13884 assert!(
13885 out[1].is_missing(),
13886 "overflowed index must be NaT, got {:?}",
13887 out[1]
13888 );
13889 assert_eq!(
13890 out[2],
13891 Scalar::Timedelta64(i64::MAX),
13892 "exact i128 accumulation must recover; a clamped running sum cannot"
13893 );
13894 }
13895
13896 #[test]
13899 fn nancumsum_timedelta_exact_path_unchanged_opz27() {
13900 let sec = 1_000_000_000_i64;
13901 let vals = vec![
13902 Scalar::Timedelta64(sec),
13903 Scalar::Timedelta64(Timedelta::NAT),
13904 Scalar::Timedelta64(2 * sec),
13905 ];
13906 let out = super::nancumsum(&vals);
13907 assert_eq!(out[0], Scalar::Timedelta64(sec));
13908 assert!(out[1].is_missing());
13909 assert_eq!(out[2], Scalar::Timedelta64(3 * sec));
13910 }
13911
13912 const DAY_NS: i64 = 86_400 * 1_000_000_000;
13913 const DT_2020: i64 = 1_577_836_800_000_000_000;
13915
13916 #[test]
13924 fn datetime64_ordering_reductions_match_pandas_axhhk() {
13925 let d = Scalar::Datetime64;
13926 let vals = vec![
13927 d(DT_2020),
13928 d(DT_2020 + 60 * DAY_NS),
13929 d(DT_2020 + 31 * DAY_NS),
13930 ];
13931
13932 assert_eq!(super::nanmin(&vals), d(DT_2020));
13933 assert_eq!(super::nanmax(&vals), d(DT_2020 + 60 * DAY_NS));
13934 assert_eq!(super::nanargmin(&vals), Some(0));
13935 assert_eq!(super::nanargmax(&vals), Some(1));
13936
13937 let span = super::nanptp(&vals);
13939 assert_eq!(span, Scalar::Timedelta64(60 * DAY_NS));
13940 assert_eq!(span.dtype(), DType::Timedelta64);
13941
13942 assert_eq!(
13943 super::nancummax(&vals),
13944 vec![
13945 d(DT_2020),
13946 d(DT_2020 + 60 * DAY_NS),
13947 d(DT_2020 + 60 * DAY_NS)
13948 ]
13949 );
13950 assert_eq!(
13951 super::nancummin(&vals),
13952 vec![d(DT_2020), d(DT_2020), d(DT_2020)]
13953 );
13954 }
13955
13956 #[test]
13963 fn datetime64_min_max_size_dependence_pinned_axhhk() {
13964 let d = Scalar::Datetime64;
13965 let one = vec![d(DT_2020)];
13966 assert_eq!(super::nanmin(&one), d(DT_2020));
13967 assert_eq!(super::nanmax(&one), d(DT_2020));
13968
13969 let two = vec![d(DT_2020 + DAY_NS), d(DT_2020)];
13970 let got_min = super::nanmin(&two);
13971 assert!(
13972 !got_min.is_missing(),
13973 "2-element datetime min must not be missing, got {got_min:?}"
13974 );
13975 assert_eq!(got_min, d(DT_2020));
13976 assert_eq!(super::nanmax(&two), d(DT_2020 + DAY_NS));
13977 }
13978
13979 #[test]
13982 fn datetime64_reductions_skip_nat_and_guard_span_overflow_axhhk() {
13983 let d = Scalar::Datetime64;
13984 let with_nat = vec![
13985 d(Timestamp::NAT),
13986 d(DT_2020 + 31 * DAY_NS),
13987 d(DT_2020),
13988 d(Timestamp::NAT),
13989 ];
13990 assert_eq!(super::nanmin(&with_nat), d(DT_2020));
13991 assert_eq!(super::nanmax(&with_nat), d(DT_2020 + 31 * DAY_NS));
13992 assert_eq!(super::nanptp(&with_nat), Scalar::Timedelta64(31 * DAY_NS));
13993 assert_eq!(super::nanargmin(&with_nat), Some(2));
13995 assert_eq!(super::nanargmax(&with_nat), Some(1));
13996
13997 let huge = vec![d(i64::MIN + 1), d(i64::MAX)];
13999 let span = super::nanptp(&huge);
14000 assert!(span.is_missing(), "unrepresentable span must be NaT");
14001 assert_ne!(span, Scalar::Timedelta64(i64::MAX));
14002 }
14003
14004 #[test]
14011 fn datetime64_averaging_reductions_match_pandas_adv58() {
14012 let d = Scalar::Datetime64;
14013 let vals = vec![
14014 d(DT_2020),
14015 d(DT_2020 + 60 * DAY_NS),
14016 d(DT_2020 + 31 * DAY_NS),
14017 ];
14018 assert_eq!(super::nanmean(&vals), d(1_580_457_600_000_000_000));
14020 assert_eq!(super::nanmedian(&vals), d(1_580_515_200_000_000_000));
14021 assert_eq!(super::nanquantile(&vals, 0.5), d(1_580_515_200_000_000_000));
14022 assert_eq!(
14023 super::nanquantile(&vals, 0.25),
14024 d(1_579_176_000_000_000_000)
14025 );
14026 }
14027
14028 #[test]
14034 fn datetime64_mean_median_round_toward_zero_adv58() {
14035 let d = Scalar::Datetime64;
14036 for (a, b, want) in [
14037 (0_i64, 1_i64, 0_i64),
14038 (0, 3, 1),
14039 (1, 2, 1),
14040 (-1, 0, 0),
14041 (-3, 0, -1),
14042 (-2, -1, -1),
14043 (0, 2, 1),
14044 (-2, 0, -1),
14045 ] {
14046 let vals = vec![d(a), d(b)];
14047 assert_eq!(
14048 super::nanmean(&vals),
14049 d(want),
14050 "mean of [{a}, {b}] should be {want}"
14051 );
14052 assert_eq!(
14053 super::nanmedian(&vals),
14054 d(want),
14055 "median of [{a}, {b}] should be {want}"
14056 );
14057 }
14058 }
14059
14060 #[test]
14063 fn datetime64_averaging_skips_nat_adv58() {
14064 let d = Scalar::Datetime64;
14065 let vals = vec![d(DT_2020), d(Timestamp::NAT), d(DT_2020 + 2 * DAY_NS)];
14066 assert_eq!(super::nanmean(&vals), d(DT_2020 + DAY_NS));
14068 assert_eq!(super::nanmedian(&vals), d(DT_2020 + DAY_NS));
14069
14070 let all_nat = vec![d(Timestamp::NAT), d(Timestamp::NAT)];
14071 let got = super::nanmean(&all_nat);
14072 assert!(
14073 got.is_missing(),
14074 "all-NaT mean must be missing, got {got:?}"
14075 );
14076 assert_eq!(
14077 got.dtype(),
14078 DType::datetime64_naive(),
14079 "must stay Datetime64"
14080 );
14081 }
14082
14083 #[test]
14090 fn datetime64_averaging_is_exact_where_pandas_snaps_adv58() {
14091 let d = Scalar::Datetime64;
14092
14093 let constant = vec![d(DT_2020 + 1), d(DT_2020 + 1)];
14095 assert_eq!(super::nanmean(&constant), d(DT_2020 + 1));
14096 assert_eq!(super::nanmedian(&constant), d(DT_2020 + 1));
14097
14098 let odd = vec![d(DT_2020), d(DT_2020 + 129), d(DT_2020 + 258)];
14100 let med = super::nanmedian(&odd);
14101 assert_eq!(med, d(DT_2020 + 129));
14102 assert!(
14103 odd.contains(&med),
14104 "odd-count median must be one of the inputs; pandas returns B+256, which is not"
14105 );
14106 }
14107
14108 #[test]
14115 fn datetime64_std_matches_pandas_ddof_variants_40ujm() {
14116 let d = Scalar::Datetime64;
14117 let vals = vec![
14118 d(DT_2020),
14119 d(DT_2020 + 60 * DAY_NS),
14120 d(DT_2020 + 31 * DAY_NS),
14121 ];
14122 let s1 = super::nanstd(&vals, 1);
14124 assert_eq!(s1, Scalar::Timedelta64(2_592_479_955_563_784));
14125 assert_eq!(s1.dtype(), DType::Timedelta64);
14126 assert_eq!(
14127 super::nanstd(&vals, 0),
14128 Scalar::Timedelta64(2_116_751_019_841_492)
14129 );
14130 assert_eq!(
14131 super::nanstd(&vals, 2),
14132 Scalar::Timedelta64(3_666_320_313_338_702)
14133 );
14134 assert!(super::nanstd(&vals, 3).is_missing());
14136 }
14137
14138 #[test]
14142 fn datetime64_std_equals_timedelta64_std_on_same_ns_40ujm() {
14143 let offsets = [0_i64, 60 * DAY_NS, 31 * DAY_NS];
14144 let dt: Vec<Scalar> = offsets.iter().map(|o| Scalar::Datetime64(*o)).collect();
14145 let td: Vec<Scalar> = offsets.iter().map(|o| Scalar::Timedelta64(*o)).collect();
14146 assert_eq!(super::nanstd(&dt, 1), super::nanstd(&td, 1));
14147 assert_eq!(
14148 super::nanstd(&dt, 1),
14149 Scalar::Timedelta64(2_592_479_955_563_784)
14150 );
14151 }
14152
14153 #[test]
14157 fn datetime64_std_skips_nat_and_var_sem_stay_unsupported_40ujm() {
14158 let d = Scalar::Datetime64;
14159 let with_nat = vec![d(DT_2020), d(Timestamp::NAT), d(DT_2020 + 2 * DAY_NS)];
14160 let without = vec![d(DT_2020), d(DT_2020 + 2 * DAY_NS)];
14161 assert_eq!(super::nanstd(&with_nat, 1), super::nanstd(&without, 1));
14163 assert_eq!(
14164 super::nanstd(&with_nat, 1),
14165 Scalar::Timedelta64(122_188_051_789_035)
14166 );
14167
14168 assert!(super::nanstd(&[d(DT_2020)], 1).is_missing());
14170 assert!(super::nanstd(&[d(Timestamp::NAT)], 1).is_missing());
14171
14172 let vals = vec![d(DT_2020), d(DT_2020 + 60 * DAY_NS)];
14176 assert!(super::nanvar(&vals, 1).is_missing());
14177 assert!(super::nansem(&vals, 1).is_missing());
14178 }
14179
14180 #[test]
14185 fn period_min_max_match_pandas_qoabs() {
14186 let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
14187 let vals = vec![p(600), p(602), p(601)];
14188 assert_eq!(super::nanmin(&vals), p(600));
14189 assert_eq!(super::nanmax(&vals), p(602));
14190
14191 assert_eq!(super::nanmin(&[p(600)]), p(600));
14195 let two = vec![p(602), p(600)];
14196 assert!(!super::nanmin(&two).is_missing());
14197 assert_eq!(super::nanmin(&two), p(600));
14198 assert_eq!(super::nanmax(&two), p(602));
14199 }
14200
14201 #[test]
14204 fn period_min_max_skip_nat_qoabs() {
14205 let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
14206 let nat = Scalar::Period(Period::new(i64::MIN, PeriodFreq::Monthly));
14207 let vals = vec![nat.clone(), p(602), p(600), nat.clone()];
14208 assert_eq!(super::nanmin(&vals), p(600));
14209 assert_eq!(super::nanmax(&vals), p(602));
14210 assert!(super::nanmin(&[nat.clone(), nat]).is_missing());
14211 }
14212
14213 #[test]
14220 fn period_mixed_freq_is_not_ordered_qoabs() {
14221 let month = Scalar::Period(Period::new(600, PeriodFreq::Monthly));
14222 let day = Scalar::Period(Period::new(18_267, PeriodFreq::Daily));
14223 let vals = vec![month.clone(), day.clone()];
14224 let got_min = super::nanmin(&vals);
14225 assert!(
14226 got_min.is_missing(),
14227 "mixed-freq Period min must not be ordered, got {got_min:?}"
14228 );
14229 assert_ne!(
14230 got_min, day,
14231 "must not rank the daily period by raw ordinal"
14232 );
14233 assert!(super::nanmax(&vals).is_missing());
14234 }
14235
14236 #[test]
14243 fn period_full_reduction_family_matches_pandas_d7zjp() {
14244 let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
14245 let vals = vec![p(600), p(602), p(601)];
14246
14247 assert_eq!(super::nanmedian(&vals), p(601));
14248 assert_eq!(super::nanquantile(&vals, 0.5), p(601));
14249 assert_eq!(super::nanargmin(&vals), Some(0));
14250 assert_eq!(super::nanargmax(&vals), Some(1));
14251 assert_eq!(super::nancummax(&vals), vec![p(600), p(602), p(602)]);
14252 assert_eq!(super::nancummin(&vals), vec![p(600), p(600), p(600)]);
14253 }
14254
14255 #[test]
14260 fn period_even_count_median_truncates_toward_zero_d7zjp() {
14261 let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
14262 assert_eq!(super::nanmedian(&[p(600), p(603)]), p(601));
14263 assert_eq!(super::nanmedian(&[p(600), p(601)]), p(600));
14264 }
14265
14266 #[test]
14272 fn period_mixed_freq_not_ordered_by_any_reduction_d7zjp() {
14273 let month = Scalar::Period(Period::new(600, PeriodFreq::Monthly));
14274 let day = Scalar::Period(Period::new(18_267, PeriodFreq::Daily));
14275 let vals = vec![month, day];
14276
14277 assert!(super::nanmedian(&vals).is_missing());
14278 assert!(super::nanquantile(&vals, 0.5).is_missing());
14279 assert_eq!(super::nanargmin(&vals), None);
14280 assert_eq!(super::nanargmax(&vals), None);
14281 assert!(super::nancummax(&vals).iter().all(Scalar::is_missing));
14283 assert!(super::nancummin(&vals).iter().all(Scalar::is_missing));
14284 }
14285
14286 #[test]
14292 fn period_unsupported_reductions_stay_missing_d7zjp() {
14293 let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
14294 let vals = vec![p(600), p(602), p(601)];
14295 assert!(super::nanstd(&vals, 1).is_missing(), "pandas raises std");
14296 assert!(super::nanvar(&vals, 1).is_missing(), "pandas raises var");
14297 assert!(super::nansem(&vals, 1).is_missing(), "pandas raises sem");
14298 assert!(super::nanmean(&vals).is_missing(), "pandas raises mean");
14299 }
14300
14301 #[test]
14306 fn interval_min_max_match_pandas_srqdo() {
14307 let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
14308 let vals = vec![iv(0.0, 1.0), iv(4.0, 5.0), iv(2.0, 3.0)];
14309 assert_eq!(super::nanmin(&vals), iv(0.0, 1.0));
14310 assert_eq!(super::nanmax(&vals), iv(4.0, 5.0));
14311
14312 assert_eq!(super::nanmin(&[iv(2.0, 3.0)]), iv(2.0, 3.0));
14315 let two = vec![iv(4.0, 5.0), iv(0.0, 1.0)];
14316 assert!(!super::nanmin(&two).is_missing());
14317 assert_eq!(super::nanmin(&two), iv(0.0, 1.0));
14318 assert_eq!(super::nanmax(&two), iv(4.0, 5.0));
14319 }
14320
14321 #[test]
14326 fn interval_ties_on_left_order_by_right_srqdo() {
14327 let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
14328 let vals = vec![iv(0.0, 5.0), iv(0.0, 2.0), iv(0.0, 9.0)];
14329 assert_eq!(super::nanmin(&vals), iv(0.0, 2.0));
14330 assert_eq!(super::nanmax(&vals), iv(0.0, 9.0));
14331 }
14332
14333 #[test]
14339 fn interval_nan_bound_is_not_ordered_srqdo() {
14340 let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
14341 let vals = vec![iv(0.0, 1.0), iv(f64::NAN, 5.0)];
14342 assert!(super::nanmin(&vals).is_missing());
14343 assert!(super::nanmax(&vals).is_missing());
14344 }
14345
14346 #[test]
14350 fn interval_unsupported_reductions_stay_missing_srqdo() {
14351 let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
14352 let vals = vec![iv(0.0, 1.0), iv(4.0, 5.0), iv(2.0, 3.0)];
14353 assert!(super::nanmedian(&vals).is_missing(), "pandas raises median");
14354 assert!(super::nanmean(&vals).is_missing(), "pandas raises mean");
14355 assert!(super::nanstd(&vals, 1).is_missing(), "pandas raises std");
14356 assert!(
14357 super::nanquantile(&vals, 0.5).is_missing(),
14358 "pandas raises quantile"
14359 );
14360 assert!(
14361 super::nancummax(&vals).iter().all(Scalar::is_missing),
14362 "pandas NotImplementedErrors cummax"
14363 );
14364 }
14365
14366 #[test]
14370 fn interval_argmin_argmax_match_pandas_2h9dm() {
14371 let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
14372 let vals = vec![iv(4.0, 5.0), iv(0.0, 1.0), iv(2.0, 3.0)];
14374 assert_eq!(super::nanargmin(&vals), Some(1));
14375 assert_eq!(super::nanargmax(&vals), Some(0));
14376
14377 let tie = vec![iv(0.0, 5.0), iv(0.0, 2.0), iv(0.0, 9.0)];
14380 assert_eq!(super::nanargmin(&tie), Some(1));
14381 assert_eq!(super::nanargmax(&tie), Some(2));
14382 }
14383
14384 #[test]
14389 fn interval_arg_first_occurrence_and_missing_2h9dm() {
14390 let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
14391 let dup = vec![iv(0.0, 1.0), iv(0.0, 1.0), iv(9.0, 9.0)];
14392 assert_eq!(
14393 super::nanargmin(&dup),
14394 Some(0),
14395 "first occurrence, not last"
14396 );
14397 assert_eq!(super::nanargmax(&dup), Some(2));
14398
14399 let with_missing = vec![iv(4.0, 5.0), Scalar::Null(NullKind::NaN), iv(0.0, 1.0)];
14400 assert_eq!(super::nanargmin(&with_missing), Some(2));
14401 assert_eq!(super::nanargmax(&with_missing), Some(0));
14402 }
14403
14404 #[test]
14408 fn interval_arg_nan_bound_declines_2h9dm() {
14409 let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
14410 let vals = vec![iv(0.0, 1.0), iv(f64::NAN, 5.0)];
14411 assert_eq!(super::nanargmin(&vals), None);
14412 assert_eq!(super::nanargmax(&vals), None);
14413 }
14414
14415 #[test]
14422 fn overflow_policy_carrier_preserves_default_behavior_f29nz() {
14423 let mut state: u64 = 0x5DEE_CE66_D125_1F00;
14425 let mut next = || {
14426 state = state
14427 .wrapping_mul(6_364_136_223_846_793_005)
14428 .wrapping_add(1_442_695_040_888_963_407);
14429 state
14430 };
14431 let mut corpus: Vec<i64> = vec![
14433 0,
14434 1,
14435 -1,
14436 2,
14437 -2,
14438 i64::MAX,
14439 i64::MIN,
14440 i64::MIN + 1,
14441 i64::MAX - 1,
14442 i64::MAX / 2,
14443 -(i64::MAX / 2),
14444 ];
14445 for _ in 0..400 {
14446 let raw = next() as i64;
14447 corpus.push(raw);
14448 corpus.push(raw / 3);
14449 }
14450
14451 let policy = super::OverflowPolicy::default();
14452 assert_eq!(
14453 policy,
14454 super::OverflowPolicy::SurfaceNat,
14455 "default must not move"
14456 );
14457
14458 for &a in &corpus {
14459 for &b in &corpus {
14460 assert_eq!(
14462 Timedelta::add(a, b),
14463 policy
14464 .resolve(Timedelta::try_add(a, b), Timedelta::NAT)
14465 .expect("SurfaceNat never errors"),
14466 "add({a}, {b}) diverged"
14467 );
14468 assert_eq!(
14469 Timedelta::sub(a, b),
14470 policy
14471 .resolve(Timedelta::try_sub(a, b), Timedelta::NAT)
14472 .expect("SurfaceNat never errors"),
14473 "sub({a}, {b}) diverged"
14474 );
14475 assert_eq!(
14476 Timedelta::mul_scalar(a, b),
14477 policy
14478 .resolve(Timedelta::try_mul_scalar(a, b), Timedelta::NAT)
14479 .expect("SurfaceNat never errors"),
14480 "mul_scalar({a}, {b}) diverged"
14481 );
14482
14483 let ts = Timestamp::from_nanos(a);
14486 assert_eq!(
14487 ts.add_timedelta(b),
14488 ts.try_add_timedelta(b).unwrap_or_else(|_| Timestamp::nat()),
14489 "add_timedelta({a}, {b}) diverged"
14490 );
14491 assert_eq!(
14492 ts.sub_timedelta(b),
14493 ts.try_sub_timedelta(b).unwrap_or_else(|_| Timestamp::nat()),
14494 "sub_timedelta({a}, {b}) diverged"
14495 );
14496 let other = Timestamp::from_nanos(b);
14497 assert_eq!(
14498 ts.sub_timestamp(&other),
14499 ts.try_sub_timestamp(&other).unwrap_or(Timedelta::NAT),
14500 "sub_timestamp({a}, {b}) diverged"
14501 );
14502 }
14503 }
14504 }
14505
14506 #[test]
14511 fn overflow_policy_strict_reports_op_and_pandas_class_f29nz() {
14512 use super::{OverflowPolicy, PandasTemporalError};
14513
14514 let strict = OverflowPolicy::Strict;
14515
14516 let err = strict
14518 .resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT)
14519 .expect_err("must surface under Strict");
14520 assert_eq!(err.op, "Timedelta::add");
14521 assert_eq!(err.pandas_error, PandasTemporalError::Overflow);
14522
14523 let ts = Timestamp::from_nanos(i64::MAX);
14525 let err = strict
14526 .resolve(ts.try_add_timedelta(1), Timestamp::nat())
14527 .expect_err("must surface under Strict");
14528 assert_eq!(err.op, "Timestamp::add_timedelta");
14529 assert_eq!(err.pandas_error, PandasTemporalError::OutOfBoundsDatetime);
14530
14531 let err = strict
14533 .resolve(
14534 Timestamp::from_nanos(i64::MIN + 1)
14535 .try_sub_timestamp(&Timestamp::from_nanos(i64::MAX)),
14536 Timedelta::NAT,
14537 )
14538 .expect_err("must surface under Strict");
14539 assert_eq!(err.op, "Timestamp::sub_timestamp");
14540 assert_eq!(err.pandas_error, PandasTemporalError::OutOfBoundsDatetime);
14541
14542 assert_eq!(
14544 strict
14545 .resolve(Timedelta::try_add(Timedelta::NAT, 1), Timedelta::NAT)
14546 .expect("NaT propagation is not an overflow"),
14547 Timedelta::NAT
14548 );
14549 assert_eq!(
14551 strict
14552 .resolve(Timedelta::try_add(2, 3), Timedelta::NAT)
14553 .expect("no overflow"),
14554 5
14555 );
14556 }
14557
14558 #[test]
14566 fn timedelta_scalar_zero_division_taxonomy_t7ht2() {
14567 use super::{OverflowPolicy, PandasTemporalError};
14568
14569 let err = Timedelta::try_div_scalar(1_000_000_000, 0)
14571 .expect_err("scalar divide-by-zero must be reportable");
14572 assert_eq!(err.op, "Timedelta::div_scalar");
14573 assert_eq!(err.pandas_error, PandasTemporalError::ZeroDivision);
14574
14575 assert_eq!(Timedelta::div_scalar(1_000_000_000, 0), Timedelta::NAT);
14579 assert_eq!(Timedelta::div_scalar(Timedelta::NAT, 0), Timedelta::NAT);
14580
14581 assert_eq!(
14584 OverflowPolicy::default()
14585 .resolve(Timedelta::try_div_scalar(1_000_000_000, 0), Timedelta::NAT)
14586 .expect("SurfaceNat never errors"),
14587 Timedelta::NAT
14588 );
14589
14590 assert_eq!(Timedelta::try_div_scalar(-7, 2), Ok(-4));
14593 assert_eq!(Timedelta::div_scalar(-7, 2), -4);
14594 assert_eq!(Timedelta::try_div_scalar(7, 2), Ok(3));
14595 assert_eq!(
14597 Timedelta::try_div_scalar(Timedelta::NAT, 2),
14598 Ok(Timedelta::NAT)
14599 );
14600 }
14601
14602 #[test]
14607 fn timedelta_constructor_error_maps_to_out_of_bounds_t7ht2() {
14608 use super::{PandasTemporalError, TimedeltaError};
14609
14610 assert_eq!(
14611 TimedeltaError::Overflow.pandas_error(),
14612 Some(PandasTemporalError::OutOfBoundsTimedelta)
14613 );
14614 assert_eq!(
14616 TimedeltaError::InvalidFormat("nonsense".into()).pandas_error(),
14617 None
14618 );
14619 assert!(Timedelta::from_unit(f64::INFINITY, "s").is_err());
14621 assert_eq!(
14622 Timedelta::from_unit(f64::INFINITY, "s")
14623 .unwrap_err()
14624 .pandas_error(),
14625 Some(PandasTemporalError::OutOfBoundsTimedelta)
14626 );
14627 }
14628
14629 #[test]
14635 fn hardened_audit_values_are_bit_identical_to_surface_nat_vllv6() {
14636 use super::{OverflowPolicy, overflow_audit};
14637
14638 overflow_audit::enable();
14639 let mut state: u64 = 0x1234_5678_9ABC_DEF0;
14640 let mut next = || {
14641 state = state
14642 .wrapping_mul(6_364_136_223_846_793_005)
14643 .wrapping_add(1_442_695_040_888_963_407);
14644 state
14645 };
14646 let mut corpus: Vec<i64> = vec![
14647 0,
14648 1,
14649 -1,
14650 2,
14651 -2,
14652 i64::MAX,
14653 i64::MIN,
14654 i64::MIN + 1,
14655 i64::MAX - 1,
14656 ];
14657 for _ in 0..120 {
14658 corpus.push(next() as i64);
14659 }
14660
14661 for &a in &corpus {
14662 for &b in &corpus {
14663 for op in [
14664 Timedelta::try_add as fn(i64, i64) -> Result<i64, super::TemporalFailure>,
14665 Timedelta::try_sub,
14666 Timedelta::try_mul_scalar,
14667 Timedelta::try_div_scalar,
14668 ] {
14669 let soft = OverflowPolicy::SurfaceNat
14670 .resolve(op(a, b), Timedelta::NAT)
14671 .expect("SurfaceNat never errors");
14672 let hard = OverflowPolicy::HardenedNat
14673 .resolve(op(a, b), Timedelta::NAT)
14674 .expect("HardenedNat never errors");
14675 assert_eq!(hard, soft, "HARDENED changed a value for ({a}, {b})");
14676 }
14677 }
14678 }
14679 overflow_audit::disable();
14680 }
14681
14682 #[test]
14687 fn hardened_audit_records_deterministic_recovery_entries_vllv6() {
14688 use super::{OverflowPolicy, PandasTemporalError, overflow_audit};
14689
14690 overflow_audit::enable();
14691 assert!(overflow_audit::is_enabled());
14692 assert!(overflow_audit::drain().is_empty(), "starts empty");
14693
14694 let _ =
14696 OverflowPolicy::HardenedNat.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
14697 let _ = OverflowPolicy::HardenedNat.resolve(Timedelta::try_add(2, 3), Timedelta::NAT);
14698 let _ =
14699 OverflowPolicy::HardenedNat.resolve(Timedelta::try_div_scalar(5, 0), Timedelta::NAT);
14700
14701 let entries = overflow_audit::drain();
14702 assert_eq!(entries.len(), 2, "only the two failures are recorded");
14703
14704 assert_eq!(entries[0].op, "Timedelta::add");
14705 assert_eq!(entries[0].pandas_error, PandasTemporalError::Overflow);
14706 assert_eq!(entries[0].operands, Some((i64::MAX, 1)));
14707 assert_eq!(entries[0].recovered_as, i64::MIN);
14708
14709 assert_eq!(entries[1].op, "Timedelta::div_scalar");
14710 assert_eq!(entries[1].pandas_error, PandasTemporalError::ZeroDivision);
14711 assert_eq!(entries[1].operands, Some((5, 0)));
14712
14713 assert!(overflow_audit::drain().is_empty());
14715
14716 let _ = OverflowPolicy::SurfaceNat.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
14718 let _ = OverflowPolicy::Strict.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
14719 assert!(
14720 overflow_audit::drain().is_empty(),
14721 "SurfaceNat/Strict must not write to the audit trail"
14722 );
14723
14724 overflow_audit::disable();
14725 assert!(!overflow_audit::is_enabled());
14726 let _ =
14728 OverflowPolicy::HardenedNat.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
14729 assert!(
14730 overflow_audit::drain().is_empty(),
14731 "disabled must not record"
14732 );
14733 }
14734
14735 #[test]
14753 fn strict_reproduces_pandas_silent_timedelta_wrap_s4lkx() {
14754 use super::{OverflowPolicy, nancumsum_with_policy};
14755
14756 assert_eq!(
14758 Timedelta::mul_scalar_with_policy(i64::MAX, 2, OverflowPolicy::Strict),
14759 -2,
14760 "STRICT must reproduce pandas' wrap, not repair it"
14761 );
14762
14763 let max = Scalar::Timedelta64(i64::MAX);
14766 let out = nancumsum_with_policy(
14767 &[max.clone(), max.clone(), max.clone()],
14768 OverflowPolicy::Strict,
14769 );
14770 assert_eq!(
14771 out,
14772 vec![
14773 Scalar::Timedelta64(i64::MAX),
14774 Scalar::Timedelta64(-2),
14775 Scalar::Timedelta64(i64::MAX - 2),
14776 ],
14777 "STRICT cumsum must reproduce pandas' int64 wraparound exactly"
14778 );
14779
14780 assert_eq!(
14782 Timedelta::mul_scalar_with_policy(Timedelta::NAT, 2, OverflowPolicy::Strict),
14783 Timedelta::NAT
14784 );
14785 }
14786
14787 #[test]
14793 fn non_strict_policies_still_refuse_to_wrap_s4lkx() {
14794 use super::{OverflowPolicy, nancumsum_with_policy, overflow_audit};
14795
14796 for policy in [OverflowPolicy::SurfaceNat, OverflowPolicy::HardenedNat] {
14797 assert_eq!(
14798 Timedelta::mul_scalar_with_policy(i64::MAX, 2, policy),
14799 Timedelta::NAT,
14800 "{policy:?} must NOT wrap"
14801 );
14802 assert_ne!(
14803 Timedelta::mul_scalar_with_policy(i64::MAX, 2, policy),
14804 -2,
14805 "{policy:?} must not reproduce the pandas quirk"
14806 );
14807 }
14808 assert_eq!(
14810 Timedelta::mul_scalar_with_policy(i64::MAX, 2, OverflowPolicy::default()),
14811 Timedelta::NAT
14812 );
14813
14814 let max = Scalar::Timedelta64(i64::MAX);
14816 let soft = nancumsum_with_policy(&[max.clone(), max.clone()], OverflowPolicy::SurfaceNat);
14817 assert!(soft[1].is_missing(), "non-STRICT cumsum must NaT, not wrap");
14818 assert_eq!(soft, super::nancumsum(&[max.clone(), max]));
14819
14820 overflow_audit::enable();
14823 let _ = Timedelta::mul_scalar_with_policy(i64::MAX, 2, OverflowPolicy::HardenedNat);
14824 assert_eq!(
14825 overflow_audit::drain().len(),
14826 1,
14827 "HARDENED must record the recovery it performed"
14828 );
14829 overflow_audit::disable();
14830 }
14831
14832 #[test]
14835 fn datetime64_mixed_input_still_falls_back_axhhk() {
14836 let vals = vec![Scalar::Datetime64(DT_2020), Scalar::Int64(5)];
14837 assert!(super::nanmin(&vals).is_missing());
14848 assert_eq!(super::nanptp(&vals), Scalar::Float64(0.0));
14849 }
14850
14851 #[test]
14852 fn nansum_nanmean_mixed_timedelta_other_falls_back_620mj() {
14853 let vals = vec![Scalar::Timedelta64(3600 * 1_000_000_000), Scalar::Int64(5)];
14857 assert_eq!(super::nansum(&vals), Scalar::Float64(5.0));
14859 }
14860
14861 #[test]
14862 fn nancount_counts_non_missing() {
14863 let vals = vec![
14864 Scalar::Int64(1),
14865 Scalar::Null(NullKind::Null),
14866 Scalar::Float64(3.0),
14867 ];
14868 assert_eq!(super::nancount(&vals), Scalar::Int64(2));
14869 }
14870
14871 #[test]
14872 fn nanany_nanall_nancount_match_scalar_oracle_zr2qg() {
14873 fn next(seed: &mut u64) -> u64 {
14876 *seed = seed
14877 .wrapping_mul(6364136223846793005)
14878 .wrapping_add(1442695040888963407);
14879 *seed
14880 }
14881
14882 fn truthy(value: &Scalar) -> Option<bool> {
14883 if value.is_missing() {
14884 return None;
14885 }
14886 match value {
14887 Scalar::Bool(value) => Some(*value),
14888 Scalar::Int64(value) => Some(*value != 0),
14889 Scalar::Float64(value) => Some(*value != 0.0),
14890 Scalar::Utf8(value) => Some(!value.is_empty()),
14891 Scalar::Timedelta64(value) => Some(*value != 0),
14892 _ => None,
14893 }
14894 }
14895
14896 fn assert_nanops(case: usize, values: &[Scalar]) {
14897 let truth_values = values.iter().filter_map(truthy).collect::<Vec<_>>();
14898 let expected_any = truth_values.iter().any(|value| *value);
14899 let expected_all = !truth_values.iter().any(|value| !*value);
14900 let expected_count = values.iter().filter(|value| !value.is_missing()).count() as i64;
14901
14902 assert_eq!(
14903 super::nanany(values),
14904 Scalar::Bool(expected_any),
14905 "case={case}: nanany mismatch for {values:?}"
14906 );
14907 assert_eq!(
14908 super::nanall(values),
14909 Scalar::Bool(expected_all),
14910 "case={case}: nanall mismatch for {values:?}"
14911 );
14912 assert_eq!(
14913 super::nancount(values),
14914 Scalar::Int64(expected_count),
14915 "case={case}: nancount mismatch for {values:?}"
14916 );
14917 }
14918
14919 assert_nanops(
14920 usize::MAX,
14921 &[
14922 Scalar::Null(NullKind::Null),
14923 Scalar::Null(NullKind::NaN),
14924 Scalar::Float64(f64::NAN),
14925 Scalar::Timedelta64(i64::MIN),
14926 ],
14927 );
14928
14929 let mut seed = 0x7a20_2f7e_5ca1_ab1e_u64;
14930 for case in 0..320 {
14931 let len = (next(&mut seed) % 89 + 1) as usize;
14932 let mut values = Vec::with_capacity(len);
14933 for pos in 0..len {
14934 let raw = (next(&mut seed) % 10_001) as i64 - 5_000;
14935 let value = match next(&mut seed) % 12 {
14936 0 => Scalar::Null(NullKind::Null),
14937 1 => Scalar::Null(NullKind::NaN),
14938 2 => Scalar::Float64(f64::NAN),
14939 3 => Scalar::Bool(raw & 1 == 0),
14940 4 => Scalar::Bool(false),
14941 5 => Scalar::Int64(raw % 17),
14942 6 => Scalar::Int64(0),
14943 7 => Scalar::Float64(raw as f64 / 23.0),
14944 8 => Scalar::Float64(0.0),
14945 9 => Scalar::Utf8(if raw & 1 == 0 {
14946 String::new()
14947 } else {
14948 format!("nanops_{case}_{pos}")
14949 }),
14950 10 => Scalar::Timedelta64(raw),
14951 _ => Scalar::Timedelta64(0),
14952 };
14953 values.push(value);
14954 }
14955 assert_nanops(case, &values);
14956 }
14957 }
14958
14959 #[test]
14960 fn nanmin_basic() {
14961 let vals = vec![
14962 Scalar::Float64(5.0),
14963 Scalar::Null(NullKind::Null),
14964 Scalar::Float64(2.0),
14965 Scalar::Float64(8.0),
14966 ];
14967 assert_eq!(super::nanmin(&vals), Scalar::Float64(2.0));
14968 }
14969
14970 #[test]
14971 fn nanmax_basic() {
14972 let vals = vec![
14973 Scalar::Float64(5.0),
14974 Scalar::Float64(f64::NAN),
14975 Scalar::Float64(8.0),
14976 ];
14977 assert_eq!(super::nanmax(&vals), Scalar::Float64(8.0));
14978 }
14979
14980 #[test]
14981 fn nanmin_nanmax_empty_returns_nan() {
14982 assert!(super::nanmin(&[]).is_missing());
14983 assert!(super::nanmax(&[]).is_missing());
14984 }
14985
14986 #[test]
14987 fn nanmin_nanmax_match_same_family_oracle_vj7ds() {
14988 fn next(seed: &mut u64) -> u64 {
14991 *seed = seed
14992 .wrapping_mul(6364136223846793005)
14993 .wrapping_add(1442695040888963407);
14994 *seed
14995 }
14996
14997 fn family_cmp(left: &Scalar, right: &Scalar) -> std::cmp::Ordering {
14998 match (left, right) {
14999 (Scalar::Bool(left), Scalar::Bool(right)) => left.cmp(right),
15000 (Scalar::Int64(left), Scalar::Int64(right)) => left.cmp(right),
15001 (Scalar::Float64(left), Scalar::Float64(right)) => {
15002 left.partial_cmp(right).expect("finite floats")
15003 }
15004 (Scalar::Utf8(left), Scalar::Utf8(right)) => left.cmp(right),
15005 (Scalar::Timedelta64(left), Scalar::Timedelta64(right)) => left.cmp(right),
15006 _ => std::cmp::Ordering::Equal,
15009 }
15010 }
15011
15012 fn assert_minmax(case: usize, family: &str, values: &[Scalar]) {
15013 let present = values
15014 .iter()
15015 .filter(|value| !value.is_missing())
15016 .cloned()
15017 .collect::<Vec<_>>();
15018 let actual_min = super::nanmin(values);
15019 let actual_max = super::nanmax(values);
15020 if present.is_empty() {
15021 assert!(
15022 actual_min.is_missing(),
15023 "case={case} family={family}: expected missing min for {values:?}, got {actual_min:?}"
15024 );
15025 assert!(
15026 actual_max.is_missing(),
15027 "case={case} family={family}: expected missing max for {values:?}, got {actual_max:?}"
15028 );
15029 return;
15030 }
15031
15032 let is_expected_family = |value: &Scalar| match family {
15033 "int" => matches!(value, Scalar::Int64(_)),
15034 "float" => matches!(value, Scalar::Float64(_)),
15035 "bool" => matches!(value, Scalar::Bool(_)),
15036 "utf8" => matches!(value, Scalar::Utf8(_)),
15037 "timedelta" => matches!(value, Scalar::Timedelta64(_)),
15038 _ => false,
15039 };
15040 assert!(
15041 present.iter().all(is_expected_family),
15042 "case={case} family={family}: mixed family escaped generator: {values:?}"
15043 );
15044
15045 let expected_min = present.iter().min_by(|left, right| family_cmp(left, right));
15046 let expected_max = present.iter().max_by(|left, right| family_cmp(left, right));
15047 assert!(
15048 actual_min.semantic_eq(expected_min.expect("min")),
15049 "case={case} family={family}: expected min {:?}, got {actual_min:?} for {values:?}",
15050 expected_min.expect("min")
15051 );
15052 assert!(
15053 actual_max.semantic_eq(expected_max.expect("max")),
15054 "case={case} family={family}: expected max {:?}, got {actual_max:?} for {values:?}",
15055 expected_max.expect("max")
15056 );
15057 }
15058
15059 let all_missing = [
15060 Scalar::Null(NullKind::Null),
15061 Scalar::Null(NullKind::NaN),
15062 Scalar::Float64(f64::NAN),
15063 Scalar::Timedelta64(i64::MIN),
15064 ];
15065 assert_minmax(usize::MAX, "all_missing", &all_missing);
15066
15067 let mut seed = 0xa11c_0aba_2e7d_f00d_u64;
15068 for case in 0..240 {
15069 let len = (next(&mut seed) % 73 + 1) as usize;
15070
15071 let mut ints = Vec::with_capacity(len);
15072 ints.push(Scalar::Int64(case as i64 - 120));
15073 for _ in 1..len {
15074 let raw = (next(&mut seed) % 1_001) as i64 - 500;
15075 ints.push(match next(&mut seed) % 6 {
15076 0 => Scalar::Null(NullKind::Null),
15077 1 => Scalar::Null(NullKind::NaN),
15078 _ => Scalar::Int64(raw),
15079 });
15080 }
15081 assert_minmax(case, "int", &ints);
15082
15083 let mut floats = Vec::with_capacity(len);
15084 floats.push(Scalar::Float64(case as f64 / 11.0));
15085 for _ in 1..len {
15086 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
15087 floats.push(match next(&mut seed) % 8 {
15088 0 | 1 => Scalar::Float64(f64::NAN),
15089 2 => Scalar::Float64(f64::INFINITY),
15090 3 => Scalar::Float64(f64::NEG_INFINITY),
15091 4 => Scalar::Float64(0.0),
15092 5 => Scalar::Float64(-0.0),
15093 _ => Scalar::Float64(raw as f64 / 41.0),
15094 });
15095 }
15096 assert_minmax(case, "float", &floats);
15097
15098 let mut bools = Vec::with_capacity(len);
15099 bools.push(Scalar::Bool(case & 1 == 0));
15100 for _ in 1..len {
15101 bools.push(match next(&mut seed) % 5 {
15102 0 => Scalar::Null(NullKind::Null),
15103 1 => Scalar::Null(NullKind::NaN),
15104 raw => Scalar::Bool(raw & 1 == 0),
15105 });
15106 }
15107 assert_minmax(case, "bool", &bools);
15108
15109 let mut utf8 = Vec::with_capacity(len);
15110 utf8.push(Scalar::Utf8(format!("minmax_{}", case % 17)));
15111 for pos in 1..len {
15112 utf8.push(match next(&mut seed) % 7 {
15113 0 => Scalar::Null(NullKind::Null),
15114 1 => Scalar::Null(NullKind::NaN),
15115 raw => Scalar::Utf8(format!("minmax_{}_{}", raw, pos % 11)),
15116 });
15117 }
15118 assert_minmax(case, "utf8", &utf8);
15119
15120 let mut timedeltas = Vec::with_capacity(len);
15121 timedeltas.push(Scalar::Timedelta64(case as i64 - 120));
15122 for _ in 1..len {
15123 let raw = (next(&mut seed) % 1_003) as i64 - 501;
15124 timedeltas.push(match next(&mut seed) % 7 {
15125 0 => Scalar::Null(NullKind::Null),
15126 1 => Scalar::Timedelta64(i64::MIN),
15127 _ => Scalar::Timedelta64(raw),
15128 });
15129 }
15130 assert_minmax(case, "timedelta", &timedeltas);
15131 }
15132 }
15133
15134 #[test]
15135 fn nanmin_nanmax_mixed_incompatible_types_returns_nan() {
15136 let vals = vec![Scalar::Int64(5), Scalar::Utf8("hello".into())];
15137 assert!(super::nanmin(&vals).is_missing());
15138 assert!(super::nanmax(&vals).is_missing());
15139
15140 let vals2 = vec![Scalar::Utf8("a".into()), Scalar::Float64(3.0)];
15141 assert!(super::nanmin(&vals2).is_missing());
15142 assert!(super::nanmax(&vals2).is_missing());
15143 }
15144
15145 #[test]
15146 fn nanmin_nanmax_compatible_numeric_types_ok() {
15147 let vals = vec![Scalar::Int64(5), Scalar::Float64(3.0), Scalar::Bool(true)];
15148 assert_eq!(super::nanmin(&vals), Scalar::Bool(true));
15149 assert_eq!(super::nanmax(&vals), Scalar::Int64(5));
15150 }
15151
15152 #[test]
15153 fn nanmin_nanmax_timedelta64_returns_timedelta_yic5m() {
15154 let one_hour = 3_600 * 1_000_000_000_i64;
15158 let vals = vec![
15159 Scalar::Timedelta64(3 * one_hour),
15160 Scalar::Timedelta64(one_hour),
15161 Scalar::Timedelta64(2 * one_hour),
15162 ];
15163 assert_eq!(super::nanmin(&vals), Scalar::Timedelta64(one_hour));
15164 assert_eq!(super::nanmax(&vals), Scalar::Timedelta64(3 * one_hour));
15165 }
15166
15167 #[test]
15168 fn nanmin_nanmax_timedelta64_skips_nat_yic5m() {
15169 let one_hour = 3_600 * 1_000_000_000_i64;
15170 let vals = vec![
15171 Scalar::Timedelta64(Timedelta::NAT),
15172 Scalar::Timedelta64(one_hour),
15173 Scalar::Timedelta64(2 * one_hour),
15174 Scalar::Timedelta64(Timedelta::NAT),
15175 ];
15176 assert_eq!(super::nanmin(&vals), Scalar::Timedelta64(one_hour));
15177 assert_eq!(super::nanmax(&vals), Scalar::Timedelta64(2 * one_hour));
15178 }
15179
15180 #[test]
15181 fn nanmedian_odd_count() {
15182 let vals = vec![
15183 Scalar::Float64(3.0),
15184 Scalar::Null(NullKind::Null),
15185 Scalar::Float64(1.0),
15186 Scalar::Float64(2.0),
15187 ];
15188 assert_eq!(super::nanmedian(&vals), Scalar::Float64(2.0));
15189 }
15190
15191 #[test]
15192 fn nanmedian_even_count() {
15193 let vals = vec![
15194 Scalar::Float64(1.0),
15195 Scalar::Float64(3.0),
15196 Scalar::Float64(2.0),
15197 Scalar::Float64(4.0),
15198 ];
15199 assert_eq!(super::nanmedian(&vals), Scalar::Float64(2.5));
15200 }
15201
15202 #[test]
15203 fn nanmedian_matches_numeric_and_timedelta_oracle_oabhi() {
15204 fn next(seed: &mut u64) -> u64 {
15207 *seed = seed
15208 .wrapping_mul(6364136223846793005)
15209 .wrapping_add(1442695040888963407);
15210 *seed
15211 }
15212
15213 fn expected_numeric(values: &[Scalar]) -> Scalar {
15214 let mut finite = values
15215 .iter()
15216 .filter(|value| !value.is_missing())
15217 .filter_map(|value| value.to_f64().ok())
15218 .filter(|value| !value.is_nan())
15219 .collect::<Vec<_>>();
15220 if finite.is_empty() {
15221 return Scalar::Null(NullKind::NaN);
15222 }
15223 finite.sort_by(|left, right| left.partial_cmp(right).expect("finite values"));
15224 let mid = finite.len() / 2;
15225 if finite.len().is_multiple_of(2) {
15226 Scalar::Float64((finite[mid - 1] + finite[mid]) / 2.0)
15227 } else {
15228 Scalar::Float64(finite[mid])
15229 }
15230 }
15231
15232 fn expected_timedelta(values: &[Scalar]) -> Scalar {
15233 let mut finite = values
15234 .iter()
15235 .filter_map(|value| match value {
15236 Scalar::Timedelta64(ns) if !value.is_missing() => Some(*ns),
15237 _ => None,
15238 })
15239 .collect::<Vec<_>>();
15240 if finite.is_empty() {
15241 return Scalar::Null(NullKind::NaN);
15242 }
15243 finite.sort_unstable();
15244 let mid = finite.len() / 2;
15245 let median = if finite.len().is_multiple_of(2) {
15246 (i128::from(finite[mid - 1]) + i128::from(finite[mid])) / 2
15247 } else {
15248 i128::from(finite[mid])
15249 };
15250 Scalar::Timedelta64(median as i64)
15251 }
15252
15253 fn assert_median(case: usize, family: &str, values: &[Scalar], expected: Scalar) {
15254 let actual = super::nanmedian(values);
15255 assert!(
15256 actual.semantic_eq(&expected),
15257 "case={case} family={family}: expected {expected:?}, got {actual:?} for {values:?}"
15258 );
15259 }
15260
15261 assert_median(
15262 usize::MAX,
15263 "numeric_all_missing",
15264 &[Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)],
15265 Scalar::Null(NullKind::NaN),
15266 );
15267 assert_median(
15268 usize::MAX - 1,
15269 "timedelta_all_missing",
15270 &[Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)],
15271 Scalar::Null(NullKind::NaN),
15272 );
15273 let beyond_f64_exact_ns = 200 * Timedelta::NANOS_PER_DAY;
15274 assert_median(
15275 usize::MAX - 2,
15276 "timedelta_odd_median_beyond_f64_exactness",
15277 &[
15278 Scalar::Timedelta64(beyond_f64_exact_ns),
15279 Scalar::Timedelta64(beyond_f64_exact_ns + 1),
15280 Scalar::Timedelta64(beyond_f64_exact_ns + 2),
15281 Scalar::Timedelta64(Timedelta::NAT),
15282 ],
15283 Scalar::Timedelta64(beyond_f64_exact_ns + 1),
15284 );
15285
15286 let mut seed = 0x0ab1_1eda_57a7_15e5_u64;
15287 for case in 0..220 {
15288 let len = (next(&mut seed) % 79 + 1) as usize;
15289
15290 let mut numeric = Vec::with_capacity(len);
15291 numeric.push(Scalar::Int64(case as i64 - 110));
15292 for _ in 1..len {
15293 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
15294 numeric.push(match next(&mut seed) % 8 {
15295 0 => Scalar::Null(NullKind::Null),
15296 1 => Scalar::Null(NullKind::NaN),
15297 2 => Scalar::Float64(f64::NAN),
15298 3 => Scalar::Bool(raw & 1 == 0),
15299 4 => Scalar::Int64(raw % 251),
15300 5 => Scalar::Float64(raw as f64 / 61.0),
15301 6 => Scalar::Float64(0.0),
15302 _ => Scalar::Float64(-0.0),
15303 });
15304 }
15305 assert_median(case, "numeric", &numeric, expected_numeric(&numeric));
15306
15307 let mut timedeltas = Vec::with_capacity(len);
15308 timedeltas.push(Scalar::Timedelta64(case as i64 - 110));
15309 for _ in 1..len {
15310 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
15311 timedeltas.push(match next(&mut seed) % 7 {
15312 0 => Scalar::Null(NullKind::Null),
15313 1 => Scalar::Timedelta64(i64::MIN),
15314 _ => Scalar::Timedelta64(raw),
15315 });
15316 }
15317 assert_median(
15318 case,
15319 "timedelta",
15320 &timedeltas,
15321 expected_timedelta(&timedeltas),
15322 );
15323 }
15324 }
15325
15326 #[test]
15327 fn nanvar_nanstd_nansem_match_numeric_and_timedelta_oracle_k7apg() {
15328 fn next(seed: &mut u64) -> u64 {
15331 *seed = seed
15332 .wrapping_mul(2862933555777941757)
15333 .wrapping_add(3037000493);
15334 *seed
15335 }
15336
15337 fn numeric_samples(values: &[Scalar]) -> Vec<f64> {
15338 values
15339 .iter()
15340 .filter(|value| !value.is_missing())
15341 .filter_map(|value| value.to_f64().ok())
15342 .collect()
15343 }
15344
15345 fn timedelta_samples(values: &[Scalar]) -> Vec<f64> {
15346 values
15347 .iter()
15348 .filter_map(|value| match value {
15349 Scalar::Timedelta64(ns) if !value.is_missing() => Some(*ns as f64),
15350 _ => None,
15351 })
15352 .collect()
15353 }
15354
15355 fn reductions_from_samples(samples: &[f64], ddof: usize) -> Option<(f64, f64, f64)> {
15356 if samples.len() <= ddof {
15357 return None;
15358 }
15359 let mean = samples.iter().sum::<f64>() / samples.len() as f64;
15360 let sum_sq = samples
15361 .iter()
15362 .map(|value| (value - mean).powi(2))
15363 .sum::<f64>();
15364 let var = sum_sq / (samples.len() - ddof) as f64;
15365 let std = var.sqrt();
15366 let sem = std / (samples.len() as f64).sqrt();
15367 Some((var, std, sem))
15368 }
15369
15370 fn expected_numeric(values: &[Scalar], ddof: usize) -> (Scalar, Scalar, Scalar) {
15371 let samples = numeric_samples(values);
15372 let Some((var, std, sem)) = reductions_from_samples(&samples, ddof) else {
15373 let missing = Scalar::Null(NullKind::NaN);
15374 return (missing.clone(), missing.clone(), missing);
15375 };
15376 (
15377 Scalar::Float64(var),
15378 Scalar::Float64(std),
15379 Scalar::Float64(sem),
15380 )
15381 }
15382
15383 fn expected_timedelta(values: &[Scalar], ddof: usize) -> (Scalar, Scalar, Scalar) {
15384 let samples = timedelta_samples(values);
15385 if samples.is_empty() {
15386 let missing = Scalar::Timedelta64(Timedelta::NAT);
15387 return (missing.clone(), missing.clone(), missing);
15388 }
15389 let Some((var, std, sem)) = reductions_from_samples(&samples, ddof) else {
15390 let missing = Scalar::Timedelta64(i64::MIN);
15391 return (missing.clone(), missing.clone(), missing);
15392 };
15393 (
15394 Scalar::Timedelta64(var as i64),
15395 Scalar::Timedelta64(std as i64),
15396 Scalar::Timedelta64(sem as i64),
15397 )
15398 }
15399
15400 fn assert_reductions(
15401 case: usize,
15402 family: &str,
15403 values: &[Scalar],
15404 ddof: usize,
15405 expected: (Scalar, Scalar, Scalar),
15406 ) {
15407 let (expected_var, expected_std, expected_sem) = expected;
15408 let actual_var = super::nanvar(values, ddof);
15409 let actual_std = super::nanstd(values, ddof);
15410 let actual_sem = super::nansem(values, ddof);
15411 assert!(
15412 actual_var.semantic_eq(&expected_var),
15413 "case={case} family={family} ddof={ddof}: expected var {expected_var:?}, got {actual_var:?} for {values:?}"
15414 );
15415 assert!(
15416 actual_std.semantic_eq(&expected_std),
15417 "case={case} family={family} ddof={ddof}: expected std {expected_std:?}, got {actual_std:?} for {values:?}"
15418 );
15419 assert!(
15420 actual_sem.semantic_eq(&expected_sem),
15421 "case={case} family={family} ddof={ddof}: expected sem {expected_sem:?}, got {actual_sem:?} for {values:?}"
15422 );
15423 }
15424
15425 let numeric_all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
15426 assert_reductions(
15427 usize::MAX,
15428 "numeric_all_missing",
15429 &numeric_all_missing,
15430 0,
15431 expected_numeric(&numeric_all_missing, 0),
15432 );
15433
15434 let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
15435 assert_reductions(
15436 usize::MAX - 1,
15437 "timedelta_all_missing",
15438 &td_all_missing,
15439 0,
15440 expected_timedelta(&td_all_missing, 0),
15441 );
15442
15443 let mut seed = 0x7a11_c0de_5eed_0421_u64;
15444 for case in 0..240 {
15445 let len = (next(&mut seed) % 83 + 1) as usize;
15446 let ddof = (next(&mut seed) % 4) as usize;
15447
15448 let mut numeric = Vec::with_capacity(len);
15449 numeric.push(Scalar::Float64(case as f64 / 13.0));
15450 for _ in 1..len {
15451 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
15452 numeric.push(match next(&mut seed) % 8 {
15453 0 => Scalar::Null(NullKind::Null),
15454 1 => Scalar::Null(NullKind::NaN),
15455 2 => Scalar::Float64(f64::NAN),
15456 3 => Scalar::Bool(raw & 1 == 0),
15457 4 => Scalar::Int64(raw % 251),
15458 5 => Scalar::Float64(raw as f64 / 73.0),
15459 6 => Scalar::Float64(0.0),
15460 _ => Scalar::Float64(-0.0),
15461 });
15462 }
15463 assert_reductions(
15464 case,
15465 "numeric",
15466 &numeric,
15467 ddof,
15468 expected_numeric(&numeric, ddof),
15469 );
15470
15471 let mut timedeltas = Vec::with_capacity(len);
15472 timedeltas.push(Scalar::Timedelta64(case as i64 - 120));
15473 for _ in 1..len {
15474 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
15475 timedeltas.push(match next(&mut seed) % 7 {
15476 0 => Scalar::Null(NullKind::Null),
15477 1 => Scalar::Timedelta64(i64::MIN),
15478 _ => Scalar::Timedelta64(raw),
15479 });
15480 }
15481 assert_reductions(
15482 case,
15483 "timedelta",
15484 &timedeltas,
15485 ddof,
15486 expected_timedelta(&timedeltas, ddof),
15487 );
15488 }
15489 }
15490
15491 #[test]
15492 fn nanvar_population() {
15493 let vals = vec![
15494 Scalar::Float64(2.0),
15495 Scalar::Float64(4.0),
15496 Scalar::Float64(4.0),
15497 Scalar::Float64(4.0),
15498 Scalar::Float64(5.0),
15499 Scalar::Float64(5.0),
15500 Scalar::Float64(7.0),
15501 Scalar::Float64(9.0),
15502 ];
15503 let var = super::nanvar(&vals, 0);
15504 assert!(matches!(var, Scalar::Float64(_)), "expected Float64");
15505 if let Scalar::Float64(v) = var {
15506 assert!((v - 4.0).abs() < 1e-10);
15507 }
15508 }
15509
15510 #[test]
15511 fn nanvar_sample_ddof1() {
15512 let vals = vec![
15513 Scalar::Float64(2.0),
15514 Scalar::Float64(4.0),
15515 Scalar::Float64(4.0),
15516 Scalar::Float64(4.0),
15517 Scalar::Float64(5.0),
15518 Scalar::Float64(5.0),
15519 Scalar::Float64(7.0),
15520 Scalar::Float64(9.0),
15521 ];
15522 let var = super::nanvar(&vals, 1);
15523 assert!(matches!(var, Scalar::Float64(_)), "expected Float64");
15524 if let Scalar::Float64(v) = var {
15525 assert!((v - 32.0 / 7.0).abs() < 1e-10);
15526 }
15527 }
15528
15529 #[test]
15530 fn nanvar_insufficient_values_returns_nan() {
15531 let vals = vec![Scalar::Float64(5.0)];
15532 assert!(super::nanvar(&vals, 1).is_missing());
15533 }
15534
15535 #[test]
15536 fn nanstd_is_sqrt_of_var() {
15537 let vals = vec![
15538 Scalar::Float64(2.0),
15539 Scalar::Float64(4.0),
15540 Scalar::Float64(4.0),
15541 Scalar::Float64(4.0),
15542 Scalar::Float64(5.0),
15543 Scalar::Float64(5.0),
15544 Scalar::Float64(7.0),
15545 Scalar::Float64(9.0),
15546 ];
15547 let std = super::nanstd(&vals, 0);
15548 assert!(matches!(std, Scalar::Float64(_)), "expected Float64");
15549 if let Scalar::Float64(v) = std {
15550 assert!((v - 2.0).abs() < 1e-10);
15551 }
15552 }
15553
15554 #[test]
15555 fn nanmedian_timedelta64_preserves_dtype_j8ntk() {
15556 let one_hour = 3_600 * 1_000_000_000_i64;
15559 let vals = vec![
15560 Scalar::Timedelta64(one_hour),
15561 Scalar::Timedelta64(2 * one_hour),
15562 Scalar::Timedelta64(3 * one_hour),
15563 ];
15564 assert_eq!(super::nanmedian(&vals), Scalar::Timedelta64(2 * one_hour));
15565 }
15566
15567 #[test]
15568 fn nanstd_timedelta64_preserves_dtype_j8ntk() {
15569 let one_hour: i64 = 3_600 * 1_000_000_000;
15573 let vals = vec![
15574 Scalar::Timedelta64(one_hour),
15575 Scalar::Timedelta64(2 * one_hour),
15576 Scalar::Timedelta64(3 * one_hour),
15577 ];
15578 let std = super::nanstd(&vals, 0);
15579 assert!(matches!(std, Scalar::Timedelta64(_)));
15580 if let Scalar::Timedelta64(ns) = std {
15581 let expected = (2.0_f64 / 3.0).sqrt() * one_hour as f64;
15582 assert!(
15583 (ns as f64 - expected).abs() < 1e6,
15584 "expected ~{expected} ns, got {ns}"
15585 );
15586 }
15587 }
15588
15589 #[test]
15590 fn nanstd_nansem_timedelta64_insufficient_returns_nat_j8ntk() {
15591 let one_hour = 3_600 * 1_000_000_000_i64;
15592 let vals = vec![Scalar::Timedelta64(one_hour)];
15593 assert_eq!(super::nanstd(&vals, 1), Scalar::Timedelta64(Timedelta::NAT));
15595 assert_eq!(super::nansem(&vals, 1), Scalar::Timedelta64(Timedelta::NAT));
15596 }
15597
15598 #[test]
15599 fn nanops_with_mixed_types() {
15600 let vals = vec![
15601 Scalar::Bool(true),
15602 Scalar::Int64(3),
15603 Scalar::Float64(6.0),
15604 Scalar::Null(NullKind::Null),
15605 ];
15606 assert_eq!(super::nansum(&vals), Scalar::Float64(10.0));
15607 assert_eq!(super::nancount(&vals), Scalar::Int64(3));
15608 }
15609
15610 #[test]
15611 fn nanops_all_missing_returns_identity() {
15612 let vals = vec![Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
15613 assert_eq!(super::nansum(&vals), Scalar::Float64(0.0));
15614 assert!(super::nanmean(&vals).is_missing());
15615 assert!(super::nanmedian(&vals).is_missing());
15616 assert!(super::nanvar(&vals, 0).is_missing());
15617 assert!(super::nanstd(&vals, 0).is_missing());
15618 }
15619
15620 #[test]
15623 fn timedelta_parse_simple_units() {
15624 use super::Timedelta;
15625 assert_eq!(Timedelta::parse("1d").unwrap(), Timedelta::NANOS_PER_DAY);
15626 assert_eq!(
15627 Timedelta::parse("2h").unwrap(),
15628 2 * Timedelta::NANOS_PER_HOUR
15629 );
15630 assert_eq!(
15631 Timedelta::parse("30m").unwrap(),
15632 30 * Timedelta::NANOS_PER_MIN
15633 );
15634 assert_eq!(
15635 Timedelta::parse("45s").unwrap(),
15636 45 * Timedelta::NANOS_PER_SEC
15637 );
15638 assert_eq!(
15639 Timedelta::parse("100ms").unwrap(),
15640 100 * Timedelta::NANOS_PER_MILLI
15641 );
15642 assert_eq!(
15643 Timedelta::parse("500us").unwrap(),
15644 500 * Timedelta::NANOS_PER_MICRO
15645 );
15646 assert_eq!(Timedelta::parse("1000ns").unwrap(), 1000);
15647 }
15648
15649 #[test]
15650 fn timedelta_parse_zero_valued_compound() {
15651 use super::Timedelta;
15652 for s in [
15659 "0 seconds",
15660 "0 second",
15661 "0 sec",
15662 "0s",
15663 "0 days",
15664 "0d",
15665 "0 hours",
15666 "0.0 hours",
15667 "0 minutes",
15668 "0ms",
15669 "0us",
15670 "0ns",
15671 "0",
15672 "0 days 0 seconds",
15673 ] {
15674 assert_eq!(Timedelta::parse(s).unwrap(), 0, "parse({s:?}) should be 0");
15675 }
15676 assert_eq!(Timedelta::parse("-0 seconds").unwrap(), 0);
15678 assert!(Timedelta::parse("0 fortnights").is_err());
15681 assert!(Timedelta::parse("seconds").is_err());
15682 }
15683
15684 #[test]
15685 fn timedelta_parse_compound() {
15686 use super::Timedelta;
15687 let expected = Timedelta::NANOS_PER_DAY
15688 + 2 * Timedelta::NANOS_PER_HOUR
15689 + 30 * Timedelta::NANOS_PER_MIN;
15690 assert_eq!(Timedelta::parse("1d 2h 30m").unwrap(), expected);
15691 assert_eq!(Timedelta::parse("1d2h30m").unwrap(), expected);
15692 }
15693
15694 #[test]
15695 fn timedelta_parse_leading_sign_spares_the_clock_part() {
15696 use super::Timedelta;
15697 const S: i64 = Timedelta::NANOS_PER_SEC;
15698 assert_eq!(Timedelta::parse("-1 days 02:03:04").unwrap(), -79_016 * S);
15701 assert_eq!(Timedelta::parse("-1 days +02:03:04").unwrap(), -79_016 * S);
15702 assert_eq!(
15703 Timedelta::parse("-3 days +23:59:59.5").unwrap(),
15704 -172_800 * S - S / 2
15705 );
15706 assert_eq!(Timedelta::parse("-0 days 01:00:00").unwrap(), 3_600 * S);
15707 assert_eq!(Timedelta::parse("-1d2h").unwrap(), -93_600 * S);
15709 assert_eq!(Timedelta::parse("-02:03:04").unwrap(), -7_384 * S);
15710 assert!(Timedelta::parse("-1 days -02:03:04").is_err());
15712 assert!(Timedelta::parse("1 days -02:00:00").is_err());
15713 }
15714
15715 #[test]
15716 fn timedelta_parse_iso8601_matches_pandas_tdiso() {
15717 use super::Timedelta;
15718 assert_eq!(Timedelta::parse("P1DT2H3M4S").unwrap(), 93_784_000_000_000);
15720 assert_eq!(Timedelta::parse("PT1H").unwrap(), 3_600_000_000_000);
15721 assert_eq!(Timedelta::parse("PT1H30M").unwrap(), 5_400_000_000_000);
15722 assert_eq!(Timedelta::parse("P1D").unwrap(), 86_400_000_000_000);
15723 assert_eq!(Timedelta::parse("P2W").unwrap(), 1_209_600_000_000_000);
15724 assert_eq!(Timedelta::parse("PT0.5S").unwrap(), 500_000_000);
15725 assert_eq!(Timedelta::parse("P1M").unwrap(), 60_000_000_000);
15727 assert_eq!(Timedelta::parse("P1H").unwrap(), 3_600_000_000_000);
15728 assert_eq!(Timedelta::parse("PT1D").unwrap(), 86_400_000_000_000);
15729 assert_eq!(Timedelta::parse("P1D1H").unwrap(), 90_000_000_000_000);
15730 assert_eq!(Timedelta::parse("-P1DT2H").unwrap(), -93_600_000_000_000);
15731 assert!(Timedelta::parse("P1Y").is_err());
15733 assert!(Timedelta::parse("p1d").is_err());
15734 assert!(Timedelta::parse("P").is_err());
15735 assert!(Timedelta::parse("PT").is_err());
15736 }
15737
15738 #[test]
15739 fn timedelta_parse_time_format() {
15740 use super::Timedelta;
15741 let expected = Timedelta::NANOS_PER_HOUR
15742 + 30 * Timedelta::NANOS_PER_MIN
15743 + 45 * Timedelta::NANOS_PER_SEC;
15744 assert_eq!(Timedelta::parse("01:30:45").unwrap(), expected);
15745 }
15746
15747 #[test]
15748 fn timedelta_parse_time_fraction_rejects_unicode_without_panic() {
15749 use super::{Timedelta, TimedeltaError};
15750 let err = Timedelta::parse("00:00:00.\u{00e9}\u{00e9}\u{00e9}\u{00e9}\u{00e9}")
15751 .expect_err("non-ASCII fractional seconds must reject");
15752 assert!(matches!(err, TimedeltaError::InvalidFormat(_)));
15753 }
15754
15755 #[test]
15756 fn timedelta_parse_time_format_rejects_overflow_without_panic() {
15757 use super::{Timedelta, TimedeltaError};
15758 let err = Timedelta::parse("9223372036854775807:00")
15759 .expect_err("oversized hour component must reject");
15760 assert!(matches!(err, TimedeltaError::InvalidFormat(_)));
15761 }
15762
15763 #[test]
15764 fn timedelta_parse_rejects_huge_value_overflow_zw3mg() {
15765 use super::{Timedelta, TimedeltaError};
15772 let huge = format!("{} days", "9".repeat(18));
15773 assert!(matches!(
15774 Timedelta::parse(&huge).expect_err("9...(18 9s) days must overflow"),
15775 TimedeltaError::Overflow
15776 ));
15777 }
15778
15779 #[test]
15780 fn timedelta_parse_nat() {
15781 use super::Timedelta;
15782 assert_eq!(Timedelta::parse("NaT").unwrap(), Timedelta::NAT);
15783 assert_eq!(Timedelta::parse("nat").unwrap(), Timedelta::NAT);
15784 }
15785
15786 #[test]
15787 fn timedelta_parse_negative() {
15788 use super::Timedelta;
15789 assert_eq!(Timedelta::parse("-1d").unwrap(), -Timedelta::NANOS_PER_DAY);
15790 }
15791
15792 #[test]
15793 fn timedelta_components() {
15794 use super::Timedelta;
15795 let nanos = Timedelta::NANOS_PER_DAY
15796 + Timedelta::NANOS_PER_HOUR
15797 + Timedelta::NANOS_PER_MIN
15798 + Timedelta::NANOS_PER_SEC
15799 + Timedelta::NANOS_PER_MILLI
15800 + 2 * Timedelta::NANOS_PER_MICRO
15801 + 3;
15802 let comp = Timedelta::components(nanos);
15803 assert_eq!(comp.days, 1);
15804 assert_eq!(comp.hours, 1);
15805 assert_eq!(comp.minutes, 1);
15806 assert_eq!(comp.seconds, 1);
15807 assert_eq!(comp.milliseconds, 1);
15808 assert_eq!(comp.microseconds, 2);
15809 assert_eq!(comp.nanoseconds, 3);
15810 }
15811
15812 #[test]
15813 fn timedelta_negative_components_floor_div() {
15814 use super::Timedelta;
15815 let neg_1s = -Timedelta::NANOS_PER_SEC;
15818 assert_eq!(Timedelta::days(neg_1s), Some(-1));
15819 assert_eq!(Timedelta::seconds(neg_1s), Some(86399));
15820 assert_eq!(Timedelta::microseconds(neg_1s), Some(0));
15821 assert_eq!(Timedelta::nanoseconds(neg_1s), Some(0));
15822 let comp = Timedelta::components(neg_1s);
15823 assert_eq!(
15824 (
15825 comp.days,
15826 comp.hours,
15827 comp.minutes,
15828 comp.seconds,
15829 comp.milliseconds,
15830 comp.microseconds,
15831 comp.nanoseconds
15832 ),
15833 (-1, 23, 59, 59, 0, 0, 0)
15834 );
15835
15836 let neg = -86_401 * Timedelta::NANOS_PER_SEC;
15838 assert_eq!(Timedelta::days(neg), Some(-2));
15839 assert_eq!(Timedelta::seconds(neg), Some(86399));
15840 }
15841
15842 #[test]
15857 fn timedelta_components_are_missing_for_nat_not_zero_406ni() {
15858 use super::Timedelta;
15859 assert_eq!(Timedelta::days(Timedelta::NAT), None);
15860 assert_eq!(Timedelta::seconds(Timedelta::NAT), None);
15861 assert_eq!(Timedelta::microseconds(Timedelta::NAT), None);
15862 assert_eq!(Timedelta::nanoseconds(Timedelta::NAT), None);
15863
15864 let one_day = Timedelta::NANOS_PER_DAY;
15869 assert_eq!(Timedelta::days(one_day), Some(1));
15870 assert_eq!(Timedelta::seconds(one_day), Some(0));
15871 assert_eq!(Timedelta::microseconds(one_day), Some(0));
15872 assert_eq!(Timedelta::nanoseconds(one_day), Some(0));
15873 }
15874
15875 #[test]
15876 fn timedelta_total_seconds() {
15877 use super::Timedelta;
15878 let nanos = 90_000_000_000i64; assert!((Timedelta::total_seconds(nanos) - 90.0).abs() < 1e-9);
15880 assert!(Timedelta::total_seconds(Timedelta::NAT).is_nan());
15881 }
15882
15883 #[test]
15884 fn timedelta_format_basic() {
15885 use super::Timedelta;
15886 assert_eq!(Timedelta::format(Timedelta::NAT), "NaT");
15887 assert_eq!(
15888 Timedelta::format(Timedelta::NANOS_PER_DAY),
15889 "1 days 00:00:00"
15890 );
15891 assert_eq!(
15892 Timedelta::format(Timedelta::NANOS_PER_DAY + 2 * Timedelta::NANOS_PER_HOUR),
15893 "1 days 02:00:00"
15894 );
15895 }
15896
15897 #[test]
15898 fn timedelta_format_subsecond_matches_pandas() {
15899 use super::Timedelta;
15900 assert_eq!(
15904 Timedelta::format(1_500_000_000), "0 days 00:00:01.500000"
15906 );
15907 assert_eq!(
15908 Timedelta::format(1_000_000), "0 days 00:00:00.001000"
15910 );
15911 assert_eq!(
15912 Timedelta::format(123_456_000), "0 days 00:00:00.123456"
15914 );
15915 assert_eq!(
15917 Timedelta::format(500), "0 days 00:00:00.000000500"
15919 );
15920 assert_eq!(Timedelta::format(123_456_789), "0 days 00:00:00.123456789");
15921 }
15922
15923 #[test]
15924 fn timedelta_format_negative_uses_python_borrow_form() {
15925 use super::Timedelta;
15926 assert_eq!(Timedelta::format(-1_000_000_000), "-1 days +23:59:59");
15930 assert_eq!(
15931 Timedelta::format(-Timedelta::NANOS_PER_DAY),
15932 "-1 days +00:00:00"
15933 );
15934 assert_eq!(
15935 Timedelta::format(-25 * Timedelta::NANOS_PER_HOUR),
15936 "-2 days +23:00:00"
15937 );
15938 assert_eq!(
15939 Timedelta::format(-1_500_000_000),
15940 "-1 days +23:59:58.500000"
15941 );
15942 assert_eq!(Timedelta::format(-500), "-1 days +23:59:59.999999500");
15943 assert_eq!(Timedelta::format(-1), "-1 days +23:59:59.999999999");
15944 }
15945
15946 #[test]
15947 #[ignore = "foreground release attribution harness"]
15948 fn timedelta_format_single_buffer_ab_5ro9h() {
15949 use std::{hint::black_box, time::Instant};
15950
15951 use super::Timedelta;
15952
15953 fn former(nanos: i64) -> String {
15954 if nanos == Timedelta::NAT {
15955 return "NaT".to_string();
15956 }
15957
15958 let days = nanos.div_euclid(Timedelta::NANOS_PER_DAY);
15959 let rem = nanos.rem_euclid(Timedelta::NANOS_PER_DAY);
15960 let hours = rem / Timedelta::NANOS_PER_HOUR;
15961 let minutes = (rem % Timedelta::NANOS_PER_HOUR) / Timedelta::NANOS_PER_MIN;
15962 let seconds = (rem % Timedelta::NANOS_PER_MIN) / Timedelta::NANOS_PER_SEC;
15963 let frac = rem % Timedelta::NANOS_PER_SEC;
15964
15965 let time_part = format!("{hours:02}:{minutes:02}:{seconds:02}");
15966 let sep = if days < 0 { "+" } else { "" };
15967 if frac > 0 {
15968 if frac % 1_000 == 0 {
15969 format!("{days} days {sep}{time_part}.{:06}", frac / 1_000)
15970 } else {
15971 format!("{days} days {sep}{time_part}.{frac:09}")
15972 }
15973 } else {
15974 format!("{days} days {sep}{time_part}")
15975 }
15976 }
15977
15978 fn candidate(nanos: i64) -> String {
15979 Timedelta::format(nanos)
15980 }
15981
15982 fn elapsed(values: &[i64], format: fn(i64) -> String) -> u128 {
15983 let started = Instant::now();
15984 let mut digest = 0_usize;
15985 for &value in values {
15986 digest = digest.wrapping_add(black_box(format(black_box(value))).len());
15987 }
15988 black_box(digest);
15989 started.elapsed().as_nanos()
15990 }
15991
15992 fn median(samples: &mut [u128]) -> u128 {
15993 samples.sort_unstable();
15994 samples[samples.len() / 2]
15995 }
15996
15997 let mut seed = 0x8f42_67a1_b3d9_c50e_u64;
15998 let values: Vec<i64> = (0..16_384)
15999 .map(|i| {
16000 seed = seed
16001 .wrapping_mul(6_364_136_223_846_793_005)
16002 .wrapping_add(1_442_695_040_888_963_407);
16003 let magnitude = (seed & i64::MAX as u64) as i64;
16004 match i % 4 {
16005 0 => magnitude - magnitude % Timedelta::NANOS_PER_SEC,
16006 1 => magnitude,
16007 2 => -(magnitude - magnitude % Timedelta::NANOS_PER_MICRO),
16008 _ => -magnitude,
16009 }
16010 })
16011 .collect();
16012
16013 for &value in &[
16014 Timedelta::NAT,
16015 0,
16016 1,
16017 -1,
16018 Timedelta::NANOS_PER_DAY,
16019 -Timedelta::NANOS_PER_DAY,
16020 i64::MAX,
16021 i64::MIN + 1,
16022 ] {
16023 assert_eq!(former(value), candidate(value));
16024 }
16025 for &value in &values {
16026 assert_eq!(former(value), candidate(value));
16027 }
16028
16029 for _ in 0..2 {
16030 black_box(elapsed(&values, former));
16031 black_box(elapsed(&values, candidate));
16032 }
16033
16034 let mut former_samples = Vec::with_capacity(18);
16035 let mut candidate_samples = Vec::with_capacity(18);
16036 for block in 0_usize..9 {
16037 if block.is_multiple_of(2) {
16038 former_samples.push(elapsed(&values, former));
16039 candidate_samples.push(elapsed(&values, candidate));
16040 candidate_samples.push(elapsed(&values, candidate));
16041 former_samples.push(elapsed(&values, former));
16042 } else {
16043 candidate_samples.push(elapsed(&values, candidate));
16044 former_samples.push(elapsed(&values, former));
16045 former_samples.push(elapsed(&values, former));
16046 candidate_samples.push(elapsed(&values, candidate));
16047 }
16048 }
16049
16050 let former_p50 = median(&mut former_samples);
16051 let candidate_p50 = median(&mut candidate_samples);
16052 eprintln!(
16053 "TIMEDELTA_FORMAT_SINGLE_BUFFER_AB rows={} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} ratio={:.6}",
16054 values.len(),
16055 former_p50 as f64 / candidate_p50 as f64,
16056 );
16057 eprintln!("TIMEDELTA_FORMAT_SINGLE_BUFFER_AB former_samples_ns={former_samples:?}");
16058 eprintln!("TIMEDELTA_FORMAT_SINGLE_BUFFER_AB candidate_samples_ns={candidate_samples:?}");
16059 }
16060
16061 #[test]
16062 fn timedelta_isoformat_basic() {
16063 use super::Timedelta;
16064 assert_eq!(Timedelta::isoformat(Timedelta::NAT), "NaT");
16065 assert_eq!(Timedelta::isoformat(0), "P0DT0H0M0S");
16066 assert_eq!(Timedelta::isoformat(Timedelta::NANOS_PER_DAY), "P1DT0H0M0S");
16067 assert_eq!(
16068 Timedelta::isoformat(
16069 Timedelta::NANOS_PER_DAY
16070 + 2 * Timedelta::NANOS_PER_HOUR
16071 + 30 * Timedelta::NANOS_PER_MIN
16072 + 45 * Timedelta::NANOS_PER_SEC
16073 ),
16074 "P1DT2H30M45S"
16075 );
16076 assert_eq!(
16077 Timedelta::isoformat(Timedelta::NANOS_PER_SEC + 500_000_000),
16078 "P0DT0H0M1.5S"
16079 );
16080 assert_eq!(
16085 Timedelta::isoformat(-(Timedelta::NANOS_PER_DAY + Timedelta::NANOS_PER_HOUR)),
16086 "P-2DT23H0M0S"
16087 );
16088 assert_eq!(Timedelta::isoformat(-1), "P-1DT23H59M59.999999999S");
16089 }
16090
16091 #[test]
16092 #[ignore = "foreground release attribution harness"]
16093 fn timedelta_isoformat_single_buffer_ab_7jra1() {
16094 use std::{hint::black_box, time::Instant};
16095
16096 use super::Timedelta;
16097
16098 fn former_impl(nanos: i64) -> String {
16099 if nanos == Timedelta::NAT {
16100 return "NaT".to_string();
16101 }
16102
16103 let negative = nanos < 0;
16104 let abs_nanos = nanos.saturating_abs();
16105 let days = abs_nanos / Timedelta::NANOS_PER_DAY;
16106 let remaining = abs_nanos % Timedelta::NANOS_PER_DAY;
16107 let hours = remaining / Timedelta::NANOS_PER_HOUR;
16108 let remaining = remaining % Timedelta::NANOS_PER_HOUR;
16109 let minutes = remaining / Timedelta::NANOS_PER_MIN;
16110 let remaining = remaining % Timedelta::NANOS_PER_MIN;
16111 let seconds = remaining / Timedelta::NANOS_PER_SEC;
16112 let sub_sec_nanos = remaining % Timedelta::NANOS_PER_SEC;
16113
16114 let mut result = String::new();
16115 if negative {
16116 result.push('-');
16117 }
16118
16119 result.push_str(&format!("P{days}DT{hours}H{minutes}M"));
16120
16121 if sub_sec_nanos == 0 {
16122 result.push_str(&format!("{seconds}S"));
16123 } else {
16124 let frac = format!("{sub_sec_nanos:09}");
16125 let trimmed = frac.trim_end_matches('0');
16126 result.push_str(&format!("{seconds}.{trimmed}S"));
16127 }
16128
16129 result
16130 }
16131
16132 fn elapsed(values: &[i64], format: impl Fn(i64) -> String) -> u128 {
16133 let start = Instant::now();
16134 let mut digest = 0_usize;
16135 for &value in values {
16136 digest = digest.wrapping_add(black_box(format(black_box(value))).len());
16137 }
16138 black_box(digest);
16139 start.elapsed().as_nanos()
16140 }
16141
16142 fn median(values: &mut [u128]) -> u128 {
16143 values.sort_unstable();
16144 values[values.len() / 2]
16145 }
16146
16147 let mut seed = 0x7d5a_4c31_91e2_b607_u64;
16148 let values: Vec<i64> = (0..16_384)
16149 .map(|i| {
16150 seed = seed
16151 .wrapping_mul(6_364_136_223_846_793_005)
16152 .wrapping_add(1_442_695_040_888_963_407);
16153 let magnitude =
16154 (seed & i64::MAX as u64) as i64 % (3_650 * Timedelta::NANOS_PER_DAY);
16155 match i % 4 {
16156 0 => magnitude - magnitude % Timedelta::NANOS_PER_SEC,
16157 1 => magnitude,
16158 2 => -(magnitude - magnitude % Timedelta::NANOS_PER_MICRO),
16159 _ => -magnitude,
16160 }
16161 })
16162 .collect();
16163
16164 for &value in &[Timedelta::NAT, 0, 1, Timedelta::NANOS_PER_DAY, i64::MAX] {
16168 assert_eq!(former_impl(value), Timedelta::isoformat(value));
16169 }
16170 for &value in values.iter().filter(|value| **value >= 0) {
16171 assert_eq!(former_impl(value), Timedelta::isoformat(value));
16172 }
16173
16174 for _ in 0..2 {
16175 black_box(elapsed(&values, former_impl));
16176 black_box(elapsed(&values, Timedelta::isoformat));
16177 }
16178
16179 let mut former = Vec::with_capacity(18);
16180 let mut candidate = Vec::with_capacity(18);
16181 for block in 0..9 {
16182 if block % 2 == 0 {
16183 former.push(elapsed(&values, former_impl));
16184 candidate.push(elapsed(&values, Timedelta::isoformat));
16185 candidate.push(elapsed(&values, Timedelta::isoformat));
16186 former.push(elapsed(&values, former_impl));
16187 } else {
16188 candidate.push(elapsed(&values, Timedelta::isoformat));
16189 former.push(elapsed(&values, former_impl));
16190 former.push(elapsed(&values, former_impl));
16191 candidate.push(elapsed(&values, Timedelta::isoformat));
16192 }
16193 }
16194
16195 let former_p50 = median(&mut former);
16196 let candidate_p50 = median(&mut candidate);
16197 eprintln!(
16198 "ISOFORMAT_AB rows={} former_p50_ns={} candidate_p50_ns={} ratio={:.6} former_ns_per_row={:.3} candidate_ns_per_row={:.3}",
16199 values.len(),
16200 former_p50,
16201 candidate_p50,
16202 former_p50 as f64 / candidate_p50 as f64,
16203 former_p50 as f64 / values.len() as f64,
16204 candidate_p50 as f64 / values.len() as f64,
16205 );
16206 eprintln!("ISOFORMAT_AB former_samples_ns={former:?}");
16207 eprintln!("ISOFORMAT_AB candidate_samples_ns={candidate:?}");
16208 }
16209
16210 #[test]
16211 fn timedelta_floor_ceil_round() {
16212 use super::Timedelta;
16213 let nanos = Timedelta::NANOS_PER_HOUR + 30 * Timedelta::NANOS_PER_MIN;
16214
16215 assert_eq!(Timedelta::floor(nanos, "h"), Timedelta::NANOS_PER_HOUR);
16217 assert_eq!(Timedelta::floor(nanos, "d"), 0);
16218
16219 assert_eq!(Timedelta::ceil(nanos, "h"), 2 * Timedelta::NANOS_PER_HOUR);
16221 assert_eq!(Timedelta::ceil(nanos, "d"), Timedelta::NANOS_PER_DAY);
16222
16223 assert_eq!(Timedelta::round(nanos, "h"), 2 * Timedelta::NANOS_PER_HOUR);
16225
16226 assert_eq!(Timedelta::floor(Timedelta::NAT, "h"), Timedelta::NAT);
16228 assert_eq!(Timedelta::ceil(Timedelta::NAT, "h"), Timedelta::NAT);
16229 assert_eq!(Timedelta::round(Timedelta::NAT, "h"), Timedelta::NAT);
16230
16231 assert_eq!(Timedelta::floor(nanos, "invalid"), Timedelta::NAT);
16233 }
16234
16235 #[test]
16236 fn timedelta_floor_ceil_negative_use_euclidean_rounding_t79yh() {
16237 use super::Timedelta;
16238
16239 assert_eq!(
16240 Timedelta::floor(-1, "s"),
16241 -Timedelta::NANOS_PER_SEC,
16242 "floor(-1ns, 1s)"
16243 );
16244 assert_eq!(Timedelta::ceil(-1, "s"), 0, "ceil(-1ns, 1s)");
16245 assert_eq!(
16246 Timedelta::floor(-1_500_000_000, "s"),
16247 -2 * Timedelta::NANOS_PER_SEC
16248 );
16249 assert_eq!(
16250 Timedelta::ceil(-1_500_000_000, "s"),
16251 -Timedelta::NANOS_PER_SEC
16252 );
16253 assert_eq!(
16254 Timedelta::floor(-Timedelta::NANOS_PER_SEC, "s"),
16255 -Timedelta::NANOS_PER_SEC
16256 );
16257 assert_eq!(
16258 Timedelta::ceil(-Timedelta::NANOS_PER_SEC, "s"),
16259 -Timedelta::NANOS_PER_SEC
16260 );
16261 assert_eq!(
16262 Timedelta::floor(1_500_000_000, "s"),
16263 Timedelta::NANOS_PER_SEC
16264 );
16265 assert_eq!(
16266 Timedelta::ceil(1_500_000_000, "s"),
16267 2 * Timedelta::NANOS_PER_SEC
16268 );
16269 }
16270
16271 #[test]
16272 fn timedelta_scalar_dtype() {
16273 let td = Scalar::Timedelta64(86_400_000_000_000);
16274 assert_eq!(td.dtype(), DType::Timedelta64);
16275 }
16276
16277 #[test]
16278 fn timedelta_scalar_is_missing() {
16279 use super::Timedelta;
16280 let valid = Scalar::Timedelta64(1000);
16281 let nat = Scalar::Timedelta64(Timedelta::NAT);
16282 assert!(!valid.is_missing());
16283 assert!(nat.is_missing());
16284 }
16285
16286 #[test]
16287 fn dtype_utf8_deserializes_legacy_aliases() {
16288 let dtype: DType = serde_json::from_str("\"str\"").unwrap();
16289 assert_eq!(dtype, DType::Utf8);
16290
16291 let dtype: DType = serde_json::from_str("\"string\"").unwrap();
16292 assert_eq!(dtype, DType::Utf8);
16293 }
16294
16295 #[test]
16296 fn datetime64_dtype_carries_timezone_00ze3() {
16297 let naive = DType::datetime64_naive();
16298 assert_eq!(naive.timezone(), None);
16299 assert_eq!(naive.display_name(), "datetime64[ns]");
16300
16301 let aware = DType::datetime64_tz("America/New_York");
16302 assert_eq!(aware.timezone(), Some("America/New_York"));
16303 assert_eq!(aware.display_name(), "datetime64[ns, America/New_York]");
16304 assert_ne!(aware, naive, "timezone must participate in dtype identity");
16305
16306 let json = serde_json::to_string(&aware).expect("serialize timezone dtype");
16307 assert_eq!(
16308 serde_json::from_str::<DType>(&json).expect("deserialize timezone dtype"),
16309 aware
16310 );
16311 }
16312
16313 #[test]
16314 fn scalar_utf8_deserializes_legacy_aliases() {
16315 let scalar: Scalar = serde_json::from_str(r#"{"kind":"str","value":"x"}"#).unwrap();
16316 assert_eq!(scalar, Scalar::Utf8("x".to_owned()));
16317
16318 let scalar: Scalar = serde_json::from_str(r#"{"kind":"string","value":"y"}"#).unwrap();
16319 assert_eq!(scalar, Scalar::Utf8("y".to_owned()));
16320 }
16321
16322 #[test]
16323 fn nancumsum_skips_nulls_and_accumulates() {
16324 let values = vec![
16325 Scalar::Float64(1.0),
16326 Scalar::Null(NullKind::NaN),
16327 Scalar::Float64(2.0),
16328 Scalar::Float64(3.0),
16329 ];
16330 let out = super::nancumsum(&values);
16331 assert!(matches!(out[0], Scalar::Float64(v) if (v - 1.0).abs() < 1e-9));
16332 assert!(out[1].is_missing());
16333 assert!(matches!(out[2], Scalar::Float64(v) if (v - 3.0).abs() < 1e-9));
16334 assert!(matches!(out[3], Scalar::Float64(v) if (v - 6.0).abs() < 1e-9));
16335 }
16336
16337 #[test]
16338 fn nancumprod_skips_nulls_and_multiplies() {
16339 let values = vec![
16340 Scalar::Float64(2.0),
16341 Scalar::Null(NullKind::NaN),
16342 Scalar::Float64(3.0),
16343 Scalar::Float64(4.0),
16344 ];
16345 let out = super::nancumprod(&values);
16346 assert!(matches!(out[0], Scalar::Float64(v) if (v - 2.0).abs() < 1e-9));
16347 assert!(out[1].is_missing());
16348 assert!(matches!(out[2], Scalar::Float64(v) if (v - 6.0).abs() < 1e-9));
16349 assert!(matches!(out[3], Scalar::Float64(v) if (v - 24.0).abs() < 1e-9));
16350 }
16351
16352 #[test]
16353 fn nancummax_tracks_running_max() {
16354 let values = vec![
16355 Scalar::Float64(1.0),
16356 Scalar::Float64(3.0),
16357 Scalar::Null(NullKind::NaN),
16358 Scalar::Float64(2.0),
16359 Scalar::Float64(5.0),
16360 ];
16361 let out = super::nancummax(&values);
16362 assert_eq!(out[0], Scalar::Float64(1.0));
16363 assert_eq!(out[1], Scalar::Float64(3.0));
16364 assert!(out[2].is_missing());
16365 assert_eq!(out[3], Scalar::Float64(3.0));
16366 assert_eq!(out[4], Scalar::Float64(5.0));
16367 }
16368
16369 #[test]
16370 fn nancummin_tracks_running_min() {
16371 let values = vec![
16372 Scalar::Float64(5.0),
16373 Scalar::Float64(3.0),
16374 Scalar::Null(NullKind::NaN),
16375 Scalar::Float64(4.0),
16376 Scalar::Float64(1.0),
16377 ];
16378 let out = super::nancummin(&values);
16379 assert_eq!(out[0], Scalar::Float64(5.0));
16380 assert_eq!(out[1], Scalar::Float64(3.0));
16381 assert!(out[2].is_missing());
16382 assert_eq!(out[3], Scalar::Float64(3.0));
16383 assert_eq!(out[4], Scalar::Float64(1.0));
16384 }
16385
16386 #[test]
16387 fn nancumsum_timedelta64_preserves_dtype_x0x91() {
16388 let one_hour = 3_600 * 1_000_000_000_i64;
16391 let values = vec![
16392 Scalar::Timedelta64(one_hour),
16393 Scalar::Timedelta64(2 * one_hour),
16394 Scalar::Timedelta64(3 * one_hour),
16395 ];
16396 let out = super::nancumsum(&values);
16397 assert_eq!(out[0], Scalar::Timedelta64(one_hour));
16398 assert_eq!(out[1], Scalar::Timedelta64(3 * one_hour));
16399 assert_eq!(out[2], Scalar::Timedelta64(6 * one_hour));
16400 }
16401
16402 #[test]
16403 fn nancummax_nancummin_timedelta64_preserves_dtype_x0x91() {
16404 let one_hour = 3_600 * 1_000_000_000_i64;
16405 let values = vec![
16406 Scalar::Timedelta64(2 * one_hour),
16407 Scalar::Timedelta64(5 * one_hour),
16408 Scalar::Timedelta64(one_hour),
16409 Scalar::Timedelta64(3 * one_hour),
16410 ];
16411 let mx = super::nancummax(&values);
16412 assert_eq!(mx[0], Scalar::Timedelta64(2 * one_hour));
16413 assert_eq!(mx[1], Scalar::Timedelta64(5 * one_hour));
16414 assert_eq!(mx[2], Scalar::Timedelta64(5 * one_hour));
16415 assert_eq!(mx[3], Scalar::Timedelta64(5 * one_hour));
16416
16417 let mn = super::nancummin(&values);
16418 assert_eq!(mn[0], Scalar::Timedelta64(2 * one_hour));
16419 assert_eq!(mn[1], Scalar::Timedelta64(2 * one_hour));
16420 assert_eq!(mn[2], Scalar::Timedelta64(one_hour));
16421 assert_eq!(mn[3], Scalar::Timedelta64(one_hour));
16422 }
16423
16424 #[test]
16425 fn nancumulative_timedelta64_skips_nat_x0x91() {
16426 let one_hour = 3_600 * 1_000_000_000_i64;
16427 let values = vec![
16428 Scalar::Timedelta64(one_hour),
16429 Scalar::Timedelta64(Timedelta::NAT),
16430 Scalar::Timedelta64(2 * one_hour),
16431 ];
16432 let cs = super::nancumsum(&values);
16433 assert_eq!(cs[0], Scalar::Timedelta64(one_hour));
16434 assert!(cs[1].is_missing());
16435 assert_eq!(cs[2], Scalar::Timedelta64(3 * one_hour));
16436 }
16437
16438 #[test]
16439 fn nancumulative_matches_numeric_and_timedelta_oracle_k63oz() {
16440 fn next(seed: &mut u64) -> u64 {
16443 *seed = seed
16444 .wrapping_mul(3202034522624059733)
16445 .wrapping_add(4354685564936845319);
16446 *seed
16447 }
16448
16449 fn assert_vec(case: usize, family: &str, op: &str, actual: &[Scalar], expected: &[Scalar]) {
16450 assert_eq!(
16451 actual.len(),
16452 expected.len(),
16453 "case={case} family={family} op={op}: length mismatch"
16454 );
16455 for (pos, (actual, expected)) in actual.iter().zip(expected.iter()).enumerate() {
16456 assert!(
16457 actual.semantic_eq(expected),
16458 "case={case} family={family} op={op} pos={pos}: expected {expected:?}, got {actual:?}"
16459 );
16460 }
16461 }
16462
16463 fn expected_numeric(
16464 values: &[Scalar],
16465 ) -> (Vec<Scalar>, Vec<Scalar>, Vec<Scalar>, Vec<Scalar>) {
16466 let mut sum = Vec::with_capacity(values.len());
16467 let mut prod = Vec::with_capacity(values.len());
16468 let mut max = Vec::with_capacity(values.len());
16469 let mut min = Vec::with_capacity(values.len());
16470 let mut running_sum = 0.0_f64;
16471 let mut running_prod = 1.0_f64;
16472 let mut running_max: Option<f64> = None;
16473 let mut running_min: Option<f64> = None;
16474
16475 for value in values {
16476 if value.is_missing() {
16477 sum.push(Scalar::Null(NullKind::NaN));
16478 prod.push(Scalar::Null(NullKind::NaN));
16479 max.push(Scalar::Null(NullKind::NaN));
16480 min.push(Scalar::Null(NullKind::NaN));
16481 continue;
16482 }
16483 let Ok(value) = value.to_f64() else {
16484 sum.push(Scalar::Null(NullKind::NaN));
16485 prod.push(Scalar::Null(NullKind::NaN));
16486 max.push(Scalar::Null(NullKind::NaN));
16487 min.push(Scalar::Null(NullKind::NaN));
16488 continue;
16489 };
16490 if value.is_nan() {
16491 sum.push(Scalar::Null(NullKind::NaN));
16492 prod.push(Scalar::Null(NullKind::NaN));
16493 max.push(Scalar::Null(NullKind::NaN));
16494 min.push(Scalar::Null(NullKind::NaN));
16495 continue;
16496 }
16497 running_sum += value;
16498 running_prod *= value;
16499 running_max = Some(running_max.map_or(value, |current| current.max(value)));
16500 running_min = Some(running_min.map_or(value, |current| current.min(value)));
16501 sum.push(Scalar::Float64(running_sum));
16502 prod.push(Scalar::Float64(running_prod));
16503 max.push(Scalar::Float64(running_max.expect("initialized")));
16504 min.push(Scalar::Float64(running_min.expect("initialized")));
16505 }
16506
16507 (sum, prod, max, min)
16508 }
16509
16510 fn expected_timedelta(values: &[Scalar]) -> (Vec<Scalar>, Vec<Scalar>, Vec<Scalar>) {
16511 let mut sum = Vec::with_capacity(values.len());
16512 let mut max = Vec::with_capacity(values.len());
16513 let mut min = Vec::with_capacity(values.len());
16514 let mut running_sum = 0_i128;
16515 let mut running_max: Option<i64> = None;
16516 let mut running_min: Option<i64> = None;
16517
16518 for value in values {
16519 if value.is_missing() {
16520 sum.push(Scalar::Null(NullKind::NaT));
16521 max.push(Scalar::Null(NullKind::NaT));
16522 min.push(Scalar::Null(NullKind::NaT));
16523 continue;
16524 }
16525 let Scalar::Timedelta64(ns) = value else {
16526 sum.push(Scalar::Null(NullKind::NaT));
16527 max.push(Scalar::Null(NullKind::NaT));
16528 min.push(Scalar::Null(NullKind::NaT));
16529 continue;
16530 };
16531 running_sum = running_sum.saturating_add(i128::from(*ns));
16532 running_max = Some(running_max.map_or(*ns, |current| current.max(*ns)));
16533 running_min = Some(running_min.map_or(*ns, |current| current.min(*ns)));
16534 sum.push(super::timedelta_ns_to_scalar(running_sum));
16537 max.push(Scalar::Timedelta64(running_max.expect("initialized")));
16538 min.push(Scalar::Timedelta64(running_min.expect("initialized")));
16539 }
16540
16541 (sum, max, min)
16542 }
16543
16544 let mut seed = 0xc0de_c63a_5eed_0421_u64;
16545 for case in 0..260 {
16546 let len = (next(&mut seed) % 89 + 1) as usize;
16547
16548 let mut numeric = Vec::with_capacity(len);
16549 numeric.push(Scalar::Int64(case as i64 - 130));
16550 for _ in 1..len {
16551 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16552 numeric.push(match next(&mut seed) % 8 {
16553 0 => Scalar::Null(NullKind::Null),
16554 1 => Scalar::Null(NullKind::NaN),
16555 2 => Scalar::Float64(f64::NAN),
16556 3 => Scalar::Bool(raw & 1 == 0),
16557 4 => Scalar::Int64(raw % 251),
16558 5 => Scalar::Float64(raw as f64 / 79.0),
16559 6 => Scalar::Float64(0.0),
16560 _ => Scalar::Float64(-0.0),
16561 });
16562 }
16563 let (sum, prod, max, min) = expected_numeric(&numeric);
16564 assert_vec(case, "numeric", "cumsum", &super::nancumsum(&numeric), &sum);
16565 assert_vec(
16566 case,
16567 "numeric",
16568 "cumprod",
16569 &super::nancumprod(&numeric),
16570 &prod,
16571 );
16572 assert_vec(case, "numeric", "cummax", &super::nancummax(&numeric), &max);
16573 assert_vec(case, "numeric", "cummin", &super::nancummin(&numeric), &min);
16574
16575 let mut timedeltas = Vec::with_capacity(len);
16576 timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
16577 for _ in 1..len {
16578 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16579 timedeltas.push(match next(&mut seed) % 7 {
16580 0 => Scalar::Null(NullKind::Null),
16581 1 => Scalar::Timedelta64(i64::MIN),
16582 _ => Scalar::Timedelta64(raw),
16583 });
16584 }
16585 let (td_sum, td_max, td_min) = expected_timedelta(&timedeltas);
16586 assert_vec(
16587 case,
16588 "timedelta",
16589 "cumsum",
16590 &super::nancumsum(&timedeltas),
16591 &td_sum,
16592 );
16593 assert_vec(
16594 case,
16595 "timedelta",
16596 "cummax",
16597 &super::nancummax(&timedeltas),
16598 &td_max,
16599 );
16600 assert_vec(
16601 case,
16602 "timedelta",
16603 "cummin",
16604 &super::nancummin(&timedeltas),
16605 &td_min,
16606 );
16607 }
16608 }
16609
16610 #[test]
16611 fn nanquantile_linear_interpolation_matches_numpy() {
16612 let values = vec![
16613 Scalar::Float64(1.0),
16614 Scalar::Float64(2.0),
16615 Scalar::Float64(3.0),
16616 Scalar::Float64(4.0),
16617 Scalar::Float64(5.0),
16618 ];
16619 let q = super::nanquantile(&values, 0.5);
16621 assert!(matches!(q, Scalar::Float64(v) if (v - 3.0).abs() < 1e-9));
16622 let q25 = super::nanquantile(&values, 0.25);
16624 assert!(matches!(q25, Scalar::Float64(v) if (v - 2.0).abs() < 1e-9));
16625 }
16626
16627 #[test]
16628 fn nanquantile_ignores_nulls() {
16629 let values = vec![
16630 Scalar::Float64(1.0),
16631 Scalar::Null(NullKind::NaN),
16632 Scalar::Float64(3.0),
16633 ];
16634 let q = super::nanquantile(&values, 0.5);
16635 assert!(matches!(q, Scalar::Float64(v) if (v - 2.0).abs() < 1e-9));
16636 }
16637
16638 #[test]
16639 fn nanquantile_empty_and_out_of_range_yield_null() {
16640 assert!(super::nanquantile(&[], 0.5).is_missing());
16641 assert!(super::nanquantile(&[Scalar::Float64(1.0)], 1.5).is_missing());
16642 assert!(super::nanquantile(&[Scalar::Float64(1.0)], -0.1).is_missing());
16643 }
16644
16645 #[test]
16646 fn nanquantile_timedelta64_preserves_dtype_5djk7() {
16647 let one_hour: i64 = 3_600 * 1_000_000_000;
16650 let vals = vec![
16651 Scalar::Timedelta64(one_hour),
16652 Scalar::Timedelta64(2 * one_hour),
16653 Scalar::Timedelta64(3 * one_hour),
16654 Scalar::Timedelta64(4 * one_hour),
16655 Scalar::Timedelta64(5 * one_hour),
16656 ];
16657 assert_eq!(
16658 super::nanquantile(&vals, 0.5),
16659 Scalar::Timedelta64(3 * one_hour)
16660 );
16661 assert_eq!(
16662 super::nanquantile(&vals, 0.0),
16663 Scalar::Timedelta64(one_hour)
16664 );
16665 assert_eq!(
16666 super::nanquantile(&vals, 1.0),
16667 Scalar::Timedelta64(5 * one_hour)
16668 );
16669 }
16670
16671 #[test]
16672 fn nanquantile_timedelta64_linear_interpolation_5djk7() {
16673 let one_hour: i64 = 3_600 * 1_000_000_000;
16674 let vals = vec![
16675 Scalar::Timedelta64(one_hour),
16676 Scalar::Timedelta64(3 * one_hour),
16677 ];
16678 assert_eq!(
16680 super::nanquantile(&vals, 0.5),
16681 Scalar::Timedelta64(2 * one_hour)
16682 );
16683 }
16684
16685 #[test]
16686 fn nanquantile_matches_numeric_and_timedelta_oracle_ecb7r() {
16687 fn next(seed: &mut u64) -> u64 {
16690 *seed = seed
16691 .wrapping_mul(3202034522624059733)
16692 .wrapping_add(4354685564936845319);
16693 *seed
16694 }
16695
16696 fn interpolated(sorted: &[f64], q: f64) -> f64 {
16697 if sorted.len() == 1 {
16698 return sorted[0];
16699 }
16700 let pos = q * (sorted.len() - 1) as f64;
16701 let lo = pos.floor() as usize;
16702 let hi = pos.ceil() as usize;
16703 if lo == hi {
16704 sorted[lo]
16705 } else {
16706 let weight = pos - lo as f64;
16707 sorted[lo] + (sorted[hi] - sorted[lo]) * weight
16708 }
16709 }
16710
16711 fn expected_numeric(values: &[Scalar], q: f64) -> Scalar {
16712 if !(0.0..=1.0).contains(&q) {
16713 return Scalar::Null(NullKind::NaN);
16714 }
16715 let mut samples = values
16716 .iter()
16717 .filter(|value| !value.is_missing())
16718 .filter_map(|value| value.to_f64().ok())
16719 .collect::<Vec<_>>();
16720 if samples.is_empty() {
16721 return Scalar::Null(NullKind::NaN);
16722 }
16723 samples.sort_by(|left, right| left.partial_cmp(right).expect("finite values"));
16724 Scalar::Float64(interpolated(&samples, q))
16725 }
16726
16727 fn expected_timedelta(values: &[Scalar], q: f64) -> Scalar {
16728 if !(0.0..=1.0).contains(&q) {
16729 return Scalar::Null(NullKind::NaN);
16730 }
16731 let mut samples = values
16732 .iter()
16733 .filter_map(|value| match value {
16734 Scalar::Timedelta64(ns) if !value.is_missing() => Some(*ns as f64),
16735 _ => None,
16736 })
16737 .collect::<Vec<_>>();
16738 if samples.is_empty() {
16739 return Scalar::Timedelta64(Timedelta::NAT);
16742 }
16743 samples.sort_by(|left, right| left.partial_cmp(right).expect("finite values"));
16744 Scalar::Timedelta64(interpolated(&samples, q) as i64)
16745 }
16746
16747 fn assert_quantile(case: usize, family: &str, values: &[Scalar], q: f64, expected: Scalar) {
16748 let actual = super::nanquantile(values, q);
16749 assert!(
16750 actual.semantic_eq(&expected),
16751 "case={case} family={family} q={q}: expected {expected:?}, got {actual:?} for {values:?}"
16752 );
16753 }
16754
16755 let numeric_all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
16756 assert_quantile(
16757 usize::MAX,
16758 "numeric_all_missing",
16759 &numeric_all_missing,
16760 0.5,
16761 expected_numeric(&numeric_all_missing, 0.5),
16762 );
16763 assert_quantile(
16764 usize::MAX - 1,
16765 "numeric_out_of_range",
16766 &[Scalar::Float64(1.0), Scalar::Float64(2.0)],
16767 1.25,
16768 Scalar::Null(NullKind::NaN),
16769 );
16770
16771 let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
16772 assert_quantile(
16773 usize::MAX - 2,
16774 "timedelta_all_missing",
16775 &td_all_missing,
16776 0.5,
16777 expected_timedelta(&td_all_missing, 0.5),
16778 );
16779 assert_quantile(
16780 usize::MAX - 3,
16781 "timedelta_out_of_range",
16782 &[Scalar::Timedelta64(1), Scalar::Timedelta64(2)],
16783 -0.25,
16784 Scalar::Null(NullKind::NaN),
16785 );
16786
16787 let mut seed = 0x4a17_1e5e_0b5e_a11d_u64;
16788 for case in 0..260 {
16789 let len = (next(&mut seed) % 83 + 1) as usize;
16790 let q = match next(&mut seed) % 8 {
16791 0 => 0.0,
16792 1 => 0.25,
16793 2 => 0.5,
16794 3 => 0.75,
16795 4 => 1.0,
16796 _ => (next(&mut seed) % 1_001) as f64 / 1_000.0,
16797 };
16798
16799 let mut numeric = Vec::with_capacity(len);
16800 numeric.push(Scalar::Int64(case as i64 - 130));
16801 for _ in 1..len {
16802 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16803 numeric.push(match next(&mut seed) % 8 {
16804 0 => Scalar::Null(NullKind::Null),
16805 1 => Scalar::Null(NullKind::NaN),
16806 2 => Scalar::Float64(f64::NAN),
16807 3 => Scalar::Bool(raw & 1 == 0),
16808 4 => Scalar::Int64(raw % 251),
16809 5 => Scalar::Float64(raw as f64 / 67.0),
16810 6 => Scalar::Float64(0.0),
16811 _ => Scalar::Float64(-0.0),
16812 });
16813 }
16814 assert_quantile(case, "numeric", &numeric, q, expected_numeric(&numeric, q));
16815
16816 let mut timedeltas = Vec::with_capacity(len);
16817 timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
16818 for _ in 1..len {
16819 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16820 timedeltas.push(match next(&mut seed) % 7 {
16821 0 => Scalar::Null(NullKind::Null),
16822 1 => Scalar::Timedelta64(i64::MIN),
16823 _ => Scalar::Timedelta64(raw),
16824 });
16825 }
16826 assert_quantile(
16827 case,
16828 "timedelta",
16829 &timedeltas,
16830 q,
16831 expected_timedelta(&timedeltas, q),
16832 );
16833 }
16834 }
16835
16836 #[test]
16837 fn nanargmax_returns_first_position() {
16838 let values = vec![
16839 Scalar::Float64(1.0),
16840 Scalar::Null(NullKind::NaN),
16841 Scalar::Float64(4.0),
16842 Scalar::Float64(4.0),
16843 Scalar::Float64(2.0),
16844 ];
16845 assert_eq!(super::nanargmax(&values), Some(2));
16846 }
16847
16848 #[test]
16849 fn nanargmin_returns_first_position() {
16850 let values = vec![
16851 Scalar::Float64(3.0),
16852 Scalar::Null(NullKind::NaN),
16853 Scalar::Float64(1.0),
16854 Scalar::Float64(1.0),
16855 ];
16856 assert_eq!(super::nanargmin(&values), Some(2));
16857 }
16858
16859 #[test]
16860 fn nanargmax_all_missing_returns_none() {
16861 let values = vec![Scalar::Null(NullKind::NaN), Scalar::Null(NullKind::Null)];
16862 assert_eq!(super::nanargmax(&values), None);
16863 assert_eq!(super::nanargmin(&values), None);
16864 }
16865
16866 #[test]
16867 fn nanargmax_nanargmin_match_numeric_and_timedelta_oracle_unkj6() {
16868 fn next(seed: &mut u64) -> u64 {
16871 *seed = seed
16872 .wrapping_mul(2862933555777941757)
16873 .wrapping_add(3037000493);
16874 *seed
16875 }
16876
16877 fn expected_numeric(values: &[Scalar], find_max: bool) -> Option<usize> {
16878 let mut best: Option<(usize, f64)> = None;
16879 for (idx, value) in values.iter().enumerate() {
16880 if value.is_missing() {
16881 continue;
16882 }
16883 let Ok(value) = value.to_f64() else {
16884 continue;
16885 };
16886 if value.is_nan() {
16887 continue;
16888 }
16889 match best {
16890 None => best = Some((idx, value)),
16891 Some((_, current))
16892 if (find_max && value > current) || (!find_max && value < current) =>
16893 {
16894 best = Some((idx, value));
16895 }
16896 _ => {}
16897 }
16898 }
16899 best.map(|(idx, _)| idx)
16900 }
16901
16902 fn expected_timedelta(values: &[Scalar], find_max: bool) -> Option<usize> {
16903 let mut best: Option<(usize, i64)> = None;
16904 for (idx, value) in values.iter().enumerate() {
16905 if value.is_missing() {
16906 continue;
16907 }
16908 let Scalar::Timedelta64(ns) = value else {
16909 continue;
16910 };
16911 match best {
16912 None => best = Some((idx, *ns)),
16913 Some((_, current))
16914 if (find_max && *ns > current) || (!find_max && *ns < current) =>
16915 {
16916 best = Some((idx, *ns));
16917 }
16918 _ => {}
16919 }
16920 }
16921 best.map(|(idx, _)| idx)
16922 }
16923
16924 fn assert_args(
16925 case: usize,
16926 family: &str,
16927 values: &[Scalar],
16928 expected_min: Option<usize>,
16929 expected_max: Option<usize>,
16930 ) {
16931 assert_eq!(
16932 super::nanargmin(values),
16933 expected_min,
16934 "case={case} family={family}: nanargmin mismatch for {values:?}"
16935 );
16936 assert_eq!(
16937 super::nanargmax(values),
16938 expected_max,
16939 "case={case} family={family}: nanargmax mismatch for {values:?}"
16940 );
16941 }
16942
16943 let all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
16944 assert_args(usize::MAX, "numeric_all_missing", &all_missing, None, None);
16945 let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
16946 assert_args(
16947 usize::MAX - 1,
16948 "timedelta_all_missing",
16949 &td_all_missing,
16950 None,
16951 None,
16952 );
16953 let positive_int64_endpoint = [
16954 Scalar::Int64(i64::MAX - 1),
16955 Scalar::Null(NullKind::Null),
16956 Scalar::Int64(i64::MAX),
16957 ];
16958 assert_args(
16959 usize::MAX - 2,
16960 "int64_positive_endpoint_exact_order",
16961 &positive_int64_endpoint,
16962 Some(0),
16963 Some(2),
16964 );
16965 let negative_int64_endpoint = [
16966 Scalar::Int64(i64::MIN + 2),
16967 Scalar::Null(NullKind::NaN),
16968 Scalar::Int64(i64::MIN + 1),
16969 ];
16970 assert_args(
16971 usize::MAX - 3,
16972 "int64_negative_endpoint_exact_order",
16973 &negative_int64_endpoint,
16974 Some(2),
16975 Some(0),
16976 );
16977
16978 let mut seed = 0xa126_5eed_ed9e_u64;
16979 for case in 0..260 {
16980 let len = (next(&mut seed) % 83 + 1) as usize;
16981
16982 let mut numeric = Vec::with_capacity(len);
16983 numeric.push(Scalar::Int64(case as i64 - 130));
16984 if len > 1 {
16985 numeric.push(Scalar::Int64(case as i64 - 130));
16986 }
16987 for _ in numeric.len()..len {
16988 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16989 numeric.push(match next(&mut seed) % 9 {
16990 0 => Scalar::Null(NullKind::Null),
16991 1 => Scalar::Null(NullKind::NaN),
16992 2 => Scalar::Float64(f64::NAN),
16993 3 => Scalar::Bool(raw & 1 == 0),
16994 4 => Scalar::Int64(raw % 211),
16995 5 => Scalar::Float64(raw as f64 / 47.0),
16996 6 => Scalar::Float64(0.0),
16997 7 => Scalar::Float64(-0.0),
16998 _ => Scalar::Float64(raw.signum() as f64 * f64::INFINITY),
16999 });
17000 }
17001 assert_args(
17002 case,
17003 "numeric",
17004 &numeric,
17005 expected_numeric(&numeric, false),
17006 expected_numeric(&numeric, true),
17007 );
17008
17009 let mut timedeltas = Vec::with_capacity(len);
17010 timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
17011 if len > 1 {
17012 timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
17013 }
17014 for _ in timedeltas.len()..len {
17015 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
17016 timedeltas.push(match next(&mut seed) % 7 {
17017 0 => Scalar::Null(NullKind::Null),
17018 1 => Scalar::Timedelta64(i64::MIN),
17019 _ => Scalar::Timedelta64(raw),
17020 });
17021 }
17022 assert_args(
17023 case,
17024 "timedelta",
17025 &timedeltas,
17026 expected_timedelta(&timedeltas, false),
17027 expected_timedelta(&timedeltas, true),
17028 );
17029 }
17030 }
17031
17032 #[test]
17033 fn nansem_matches_std_over_sqrt_n() {
17034 let values = vec![
17035 Scalar::Float64(2.0),
17036 Scalar::Float64(4.0),
17037 Scalar::Float64(4.0),
17038 Scalar::Float64(4.0),
17039 Scalar::Float64(5.0),
17040 Scalar::Float64(5.0),
17041 Scalar::Float64(7.0),
17042 Scalar::Float64(9.0),
17043 ];
17044 let sem = super::nansem(&values, 1);
17046 assert!(matches!(sem, Scalar::Float64(_)));
17047 let Scalar::Float64(v) = sem else {
17048 return;
17049 };
17050 assert!((v - 0.7559289460184544).abs() < 1e-9);
17051 }
17052
17053 #[test]
17054 fn nansem_grouped_is_sqrt_var_over_n_7hxqv() {
17055 let values = [
17058 Scalar::Float64(1.0),
17059 Scalar::Null(NullKind::NaN),
17060 Scalar::Float64(4.0),
17061 ];
17062 assert_eq!(super::nansem_grouped(&values, 1), Scalar::Float64(1.5));
17063 assert_eq!(
17065 super::nansem(&values, 1),
17066 Scalar::Float64(1.499_999_999_999_999_8)
17067 );
17068 assert!(super::nansem_grouped(&values[..1], 1).is_missing());
17069 }
17070
17071 #[test]
17072 fn grouped_reducers_add_as_pandas_group_kernels_xhogl() {
17073 let tenths: Vec<Scalar> = (0..10).map(|_| Scalar::Float64(0.1)).collect();
17077 assert_eq!(super::nansum_grouped(&tenths), Scalar::Float64(1.0));
17078 assert_eq!(super::nanmean_grouped(&tenths), Scalar::Float64(0.1));
17079 assert_eq!(super::nanvar_grouped(&tenths, 1), Scalar::Float64(0.0));
17080 assert_eq!(super::nanstd_grouped(&tenths, 1), Scalar::Float64(0.0));
17081 assert_eq!(
17083 super::nansum(&tenths),
17084 Scalar::Float64(0.999_999_999_999_999_9)
17085 );
17086 let mut sum = super::KahanSum::default();
17088 for value in [1.0, f64::INFINITY, 2.0] {
17089 sum.add(value);
17090 }
17091 assert_eq!(sum.sum(), f64::INFINITY);
17092 let gapped = [
17094 Scalar::Float64(1.0),
17095 Scalar::Null(NullKind::NaN),
17096 Scalar::Float64(4.0),
17097 ];
17098 assert_eq!(super::nanmean_grouped(&gapped), Scalar::Float64(2.5));
17099 assert_eq!(super::nanvar_grouped(&gapped, 1), Scalar::Float64(4.5));
17100 assert!(super::nanvar_grouped(&gapped[..1], 1).is_missing());
17101 let spans = [Scalar::Timedelta64(1), Scalar::Timedelta64(2)];
17103 assert_eq!(super::nansum_grouped(&spans), super::nansum(&spans));
17104 }
17105
17106 #[test]
17107 fn grouped_skew_is_pandas_online_group_skew_vjfq9() {
17108 let group = [
17111 Scalar::Float64(1.0),
17112 Scalar::Null(NullKind::NaN),
17113 Scalar::Float64(4.0),
17114 Scalar::Float64(8.0),
17115 ];
17116 assert_eq!(
17117 super::nanskew_grouped(&group),
17118 Scalar::Float64(0.423_273_160_268_006_15)
17119 );
17120 let long: Vec<Scalar> = (0..2922_i32)
17123 .map(|i| Scalar::Float64(f64::from((i * 7919) % 1000) / 7.0))
17124 .collect();
17125 let glibc_pow = Scalar::Float64(-0.002_284_383_734_800_801_4);
17126 if cfg!(all(target_os = "linux", target_env = "gnu")) {
17132 assert_eq!(super::nanskew_grouped(&long), glibc_pow);
17133 } else {
17134 let sqrt = Scalar::Float64(-0.002_284_383_734_800_802);
17135 assert!([glibc_pow, sqrt].contains(&super::nanskew_grouped(&long)));
17136 }
17137 let constant = [7.0; 3].map(Scalar::Float64);
17140 assert_eq!(super::nanskew_grouped(&constant), Scalar::Float64(0.0));
17141 assert!(super::nanskew_grouped(&group[..2]).is_missing());
17142 let with_inf = [1.0, f64::INFINITY, 2.0, 5.0].map(Scalar::Float64);
17143 assert!(super::nanskew_grouped(&with_inf).is_missing());
17144 }
17145
17146 #[test]
17147 fn nansem_single_buffer_matches_former_numeric_bits_jgwg4() {
17148 fn former(values: &[Scalar], ddof: usize) -> Scalar {
17149 let nums = super::collect_finite(values);
17150 if nums.len() <= ddof {
17151 return Scalar::Null(NullKind::NaN);
17152 }
17153 match super::nanstd(values, ddof) {
17154 Scalar::Float64(std) => Scalar::Float64(std / (nums.len() as f64).sqrt()),
17155 other => other,
17156 }
17157 }
17158
17159 fn assert_same_bits(values: &[Scalar], ddof: usize) {
17160 let expected = former(values, ddof);
17161 let actual = super::nansem(values, ddof);
17162 match (&expected, &actual) {
17163 (Scalar::Float64(expected), Scalar::Float64(actual)) => {
17164 assert_eq!(
17165 actual.to_bits(),
17166 expected.to_bits(),
17167 "values={values:?} ddof={ddof}"
17168 );
17169 }
17170 _ => assert!(
17171 actual.semantic_eq(&expected),
17172 "values={values:?} ddof={ddof}: expected {expected:?}, got {actual:?}"
17173 ),
17174 }
17175 }
17176
17177 let mut generated = Vec::with_capacity(4_096);
17178 for idx in 0..4_096_i64 {
17179 generated.push(match idx % 257 {
17180 0 => Scalar::Null(NullKind::NaN),
17181 1 => Scalar::Float64(-0.0),
17182 2 => Scalar::Float64(0.0),
17183 _ if idx % 2 == 0 => Scalar::Int64(idx - 2_048),
17184 _ => Scalar::Float64((idx - 2_048) as f64 / 17.0),
17185 });
17186 }
17187
17188 let cases = [
17189 Vec::new(),
17190 vec![Scalar::Int64(1)],
17191 vec![
17192 Scalar::Null(NullKind::Null),
17193 Scalar::Float64(f64::NAN),
17194 Scalar::Int64(i64::MIN),
17195 Scalar::Int64(i64::MAX),
17196 Scalar::Float64(-0.0),
17197 Scalar::Float64(0.0),
17198 ],
17199 generated,
17200 ];
17201 for values in &cases {
17202 for ddof in [0, 1, values.len(), values.len().saturating_add(1)] {
17203 assert_same_bits(values, ddof);
17204 }
17205 }
17206 }
17207
17208 #[test]
17209 #[ignore = "foreground release A/B harness"]
17210 fn nansem_single_buffer_allocator_preconditioned_ab_jgwg4() {
17211 const ROWS: usize = 262_144;
17212 const BATCH: usize = 8;
17213 const BLOCKS: usize = 9;
17214 const PRECONDITION_CALLS: usize = 2;
17215
17216 fn former(values: &[Scalar], ddof: usize) -> Scalar {
17217 let nums = super::collect_finite(values);
17218 if nums.len() <= ddof {
17219 return Scalar::Null(NullKind::NaN);
17220 }
17221 match super::nanstd(values, ddof) {
17222 Scalar::Float64(std) => Scalar::Float64(std / (nums.len() as f64).sqrt()),
17223 other => other,
17224 }
17225 }
17226
17227 fn evaluate(values: &[Scalar], candidate: bool) -> Scalar {
17228 let values = std::hint::black_box(values);
17229 if candidate {
17230 super::nansem(values, 1)
17231 } else {
17232 former(values, 1)
17233 }
17234 }
17235
17236 fn elapsed_ns(values: &[Scalar], candidate: bool) -> u128 {
17237 for _ in 0..PRECONDITION_CALLS {
17238 std::hint::black_box(evaluate(values, candidate));
17239 }
17240 let started = std::time::Instant::now();
17241 for _ in 0..BATCH {
17242 std::hint::black_box(evaluate(values, candidate));
17243 }
17244 started.elapsed().as_nanos()
17245 }
17246
17247 fn median(mut samples: Vec<u128>) -> u128 {
17248 samples.sort_unstable();
17249 samples[samples.len() / 2]
17250 }
17251
17252 fn spread(a: u128, b: u128) -> f64 {
17253 a.abs_diff(b) as f64 / ((a + b) as f64 / 2.0)
17254 }
17255
17256 let values = (0..ROWS)
17257 .map(|idx| {
17258 if idx % 257 == 0 {
17259 Scalar::Null(NullKind::NaN)
17260 } else {
17261 Scalar::Int64((idx % 8_191) as i64 - 4_095)
17262 }
17263 })
17264 .collect::<Vec<_>>();
17265
17266 let expected_bits = match former(&values, 1) {
17267 Scalar::Float64(value) => Some(value.to_bits()),
17268 _ => None,
17269 };
17270 let actual_bits = match super::nansem(&values, 1) {
17271 Scalar::Float64(value) => Some(value.to_bits()),
17272 _ => None,
17273 };
17274 assert!(
17275 expected_bits.is_some(),
17276 "numeric nansem must return Float64"
17277 );
17278 assert_eq!(actual_bits, expected_bits, "A/B output bits");
17279
17280 std::hint::black_box(evaluate(&values, false));
17281 std::hint::black_box(evaluate(&values, true));
17282
17283 let body_started = std::time::Instant::now();
17284 let mut former_a = Vec::with_capacity(BLOCKS);
17285 let mut former_b = Vec::with_capacity(BLOCKS);
17286 let mut candidate_a = Vec::with_capacity(BLOCKS);
17287 let mut candidate_b = Vec::with_capacity(BLOCKS);
17288 for block in 0..BLOCKS {
17289 let order = if block % 2 == 0 {
17290 [(false, 0), (true, 0), (true, 1), (false, 1)]
17291 } else {
17292 [(true, 1), (false, 1), (false, 0), (true, 0)]
17293 };
17294 for (candidate, duplicate) in order {
17295 let elapsed = elapsed_ns(&values, candidate);
17296 match (candidate, duplicate) {
17297 (false, 0) => former_a.push(elapsed),
17298 (false, _) => former_b.push(elapsed),
17299 (true, 0) => candidate_a.push(elapsed),
17300 (true, _) => candidate_b.push(elapsed),
17301 }
17302 }
17303 }
17304
17305 let former_a = median(former_a) / BATCH as u128;
17306 let former_b = median(former_b) / BATCH as u128;
17307 let candidate_a = median(candidate_a) / BATCH as u128;
17308 let candidate_b = median(candidate_b) / BATCH as u128;
17309 let former_mean = (former_a + former_b) as f64 / 2.0;
17310 let candidate_mean = (candidate_a + candidate_b) as f64 / 2.0;
17311 println!(
17312 "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}",
17313 spread(former_a, former_b),
17314 spread(candidate_a, candidate_b),
17315 former_mean / candidate_mean,
17316 body_started.elapsed().as_secs_f64()
17317 );
17318 }
17319
17320 #[test]
17321 fn nansem_empty_returns_null() {
17322 assert!(super::nansem(&[], 1).is_missing());
17323 assert!(super::nansem(&[Scalar::Float64(1.0)], 1).is_missing());
17324 }
17325
17326 #[test]
17327 fn nanptp_returns_max_minus_min() {
17328 let values = vec![
17329 Scalar::Float64(3.0),
17330 Scalar::Null(NullKind::NaN),
17331 Scalar::Float64(7.0),
17332 Scalar::Float64(1.0),
17333 ];
17334 assert_eq!(super::nanptp(&values), Scalar::Float64(6.0));
17335 }
17336
17337 #[test]
17338 fn nanptp_empty_returns_null() {
17339 assert!(super::nanptp(&[]).is_missing());
17340 assert!(super::nanptp(&[Scalar::Null(NullKind::NaN)]).is_missing());
17341 }
17342
17343 #[test]
17344 fn nanptp_timedelta64_preserves_dtype_u2g0r() {
17345 let one_hour: i64 = 3_600 * 1_000_000_000;
17347 let values = vec![
17348 Scalar::Timedelta64(one_hour),
17349 Scalar::Timedelta64(5 * one_hour),
17350 Scalar::Timedelta64(2 * one_hour),
17351 ];
17352 assert_eq!(super::nanptp(&values), Scalar::Timedelta64(4 * one_hour));
17353 }
17354
17355 #[test]
17356 fn nanptp_matches_numeric_and_timedelta_oracle_affjt() {
17357 fn next(seed: &mut u64) -> u64 {
17360 *seed = seed
17361 .wrapping_mul(3202034522624059733)
17362 .wrapping_add(4354685564936845319);
17363 *seed
17364 }
17365
17366 fn expected_numeric(values: &[Scalar]) -> Scalar {
17367 let mut lo = f64::INFINITY;
17368 let mut hi = f64::NEG_INFINITY;
17369 let mut seen = false;
17370 for value in values {
17371 if value.is_missing() {
17372 continue;
17373 }
17374 if let Ok(value) = value.to_f64() {
17375 seen = true;
17376 lo = lo.min(value);
17377 hi = hi.max(value);
17378 }
17379 }
17380 if seen {
17381 Scalar::Float64(hi - lo)
17382 } else {
17383 Scalar::Null(NullKind::NaN)
17384 }
17385 }
17386
17387 fn expected_timedelta(values: &[Scalar]) -> Scalar {
17388 let mut lo = i64::MAX;
17389 let mut hi = i64::MIN;
17390 let mut seen = false;
17391 for value in values {
17392 if let Scalar::Timedelta64(ns) = value
17393 && !value.is_missing()
17394 {
17395 seen = true;
17396 lo = lo.min(*ns);
17397 hi = hi.max(*ns);
17398 }
17399 }
17400 if seen {
17401 Scalar::Timedelta64(hi - lo)
17402 } else {
17403 Scalar::Null(NullKind::NaN)
17404 }
17405 }
17406
17407 fn assert_ptp(case: usize, family: &str, values: &[Scalar], expected: Scalar) {
17408 let actual = super::nanptp(values);
17409 assert!(
17410 actual.semantic_eq(&expected),
17411 "case={case} family={family}: expected {expected:?}, got {actual:?} for {values:?}"
17412 );
17413 }
17414
17415 assert_ptp(
17416 usize::MAX,
17417 "numeric_all_missing",
17418 &[Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)],
17419 Scalar::Null(NullKind::NaN),
17420 );
17421 assert_ptp(
17422 usize::MAX - 1,
17423 "timedelta_all_missing",
17424 &[Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)],
17425 Scalar::Null(NullKind::NaN),
17426 );
17427 let beyond_f64_exact_ns = 200 * Timedelta::NANOS_PER_DAY;
17428 assert_ptp(
17429 usize::MAX - 2,
17430 "timedelta_one_ns_range_beyond_f64_exactness",
17431 &[
17432 Scalar::Timedelta64(beyond_f64_exact_ns),
17433 Scalar::Timedelta64(beyond_f64_exact_ns - 1),
17434 Scalar::Timedelta64(Timedelta::NAT),
17435 ],
17436 Scalar::Timedelta64(1),
17437 );
17438
17439 let mut seed = 0xa22f_17ed_57a7_15e5_u64;
17440 for case in 0..260 {
17441 let len = (next(&mut seed) % 83 + 1) as usize;
17442
17443 let mut numeric = Vec::with_capacity(len);
17444 numeric.push(Scalar::Int64(case as i64 - 130));
17445 for _ in 1..len {
17446 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
17447 numeric.push(match next(&mut seed) % 9 {
17448 0 => Scalar::Null(NullKind::Null),
17449 1 => Scalar::Null(NullKind::NaN),
17450 2 => Scalar::Float64(f64::NAN),
17451 3 => Scalar::Bool(raw & 1 == 0),
17452 4 => Scalar::Int64(raw),
17453 5 => Scalar::Float64(raw as f64 / 53.0),
17454 6 => Scalar::Float64(0.0),
17455 7 => Scalar::Float64(-0.0),
17456 _ => Scalar::Float64(raw.signum() as f64 * f64::INFINITY),
17457 });
17458 }
17459 assert_ptp(case, "numeric", &numeric, expected_numeric(&numeric));
17460
17461 let mut timedeltas = Vec::with_capacity(len);
17462 timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
17463 for _ in 1..len {
17464 let raw = (next(&mut seed) % 10_001) as i64 - 5_000;
17465 timedeltas.push(match next(&mut seed) % 7 {
17466 0 => Scalar::Null(NullKind::Null),
17467 1 => Scalar::Timedelta64(i64::MIN),
17468 _ => Scalar::Timedelta64(raw),
17469 });
17470 }
17471 assert_ptp(
17472 case,
17473 "timedelta",
17474 &timedeltas,
17475 expected_timedelta(&timedeltas),
17476 );
17477 }
17478 }
17479
17480 #[test]
17481 fn nanargmax_nanargmin_timedelta64_compare_by_ns_ql1t5() {
17482 let one_hour: i64 = 3_600 * 1_000_000_000;
17485 let values = vec![
17486 Scalar::Timedelta64(2 * one_hour),
17487 Scalar::Timedelta64(5 * one_hour),
17488 Scalar::Timedelta64(one_hour),
17489 Scalar::Timedelta64(3 * one_hour),
17490 ];
17491 assert_eq!(super::nanargmax(&values), Some(1));
17492 assert_eq!(super::nanargmin(&values), Some(2));
17493 }
17494
17495 #[test]
17496 fn nanprod_timedelta64_returns_null_szq6a() {
17497 let one_hour: i64 = 3_600 * 1_000_000_000;
17501 let values = vec![
17502 Scalar::Timedelta64(2 * one_hour),
17503 Scalar::Timedelta64(3 * one_hour),
17504 ];
17505 assert!(super::nanprod(&values).is_missing());
17506 }
17507
17508 #[test]
17509 fn nanprod_matches_numeric_and_timedelta_oracle_9938h() {
17510 fn next(seed: &mut u64) -> u64 {
17513 *seed = seed
17514 .wrapping_mul(6364136223846793005)
17515 .wrapping_add(1442695040888963407);
17516 *seed
17517 }
17518
17519 fn expected_numeric(values: &[Scalar]) -> Scalar {
17520 let mut product = 1.0_f64;
17521 for value in values {
17522 if value.is_missing() {
17523 continue;
17524 }
17525 if let Ok(value) = value.to_f64() {
17526 product *= value;
17527 }
17528 }
17529 Scalar::Float64(product)
17530 }
17531
17532 fn expected_timedelta(values: &[Scalar]) -> Scalar {
17533 if values
17534 .iter()
17535 .any(|value| matches!(value, Scalar::Timedelta64(_)) && !value.is_missing())
17536 {
17537 Scalar::Null(NullKind::NaN)
17538 } else {
17539 Scalar::Float64(1.0)
17540 }
17541 }
17542
17543 fn assert_prod(case: usize, family: &str, values: &[Scalar], expected: Scalar) {
17544 let actual = super::nanprod(values);
17545 assert!(
17546 actual.semantic_eq(&expected),
17547 "case={case} family={family}: expected {expected:?}, got {actual:?} for {values:?}"
17548 );
17549 }
17550
17551 let all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
17552 assert_prod(
17553 usize::MAX,
17554 "numeric_all_missing",
17555 &all_missing,
17556 Scalar::Float64(1.0),
17557 );
17558
17559 let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
17560 assert_prod(
17561 usize::MAX - 1,
17562 "timedelta_all_missing",
17563 &td_all_missing,
17564 expected_timedelta(&td_all_missing),
17565 );
17566
17567 let mut seed = 0x6e0d_9938_a11c_0de5_u64;
17568 for case in 0..280 {
17569 let len = (next(&mut seed) % 89 + 1) as usize;
17570
17571 let mut numeric = Vec::with_capacity(len);
17572 numeric.push(Scalar::Int64((case % 17) as i64 - 8));
17573 for _ in 1..len {
17574 let raw = (next(&mut seed) % 2_001) as i64 - 1_000;
17575 numeric.push(match next(&mut seed) % 9 {
17576 0 => Scalar::Null(NullKind::Null),
17577 1 => Scalar::Null(NullKind::NaN),
17578 2 => Scalar::Float64(f64::NAN),
17579 3 => Scalar::Bool(raw & 1 == 0),
17580 4 => Scalar::Int64(raw % 19),
17581 5 => Scalar::Float64(raw as f64 / 97.0),
17582 6 => Scalar::Float64(0.0),
17583 7 => Scalar::Float64(-0.0),
17584 _ => Scalar::Float64(1.0),
17585 });
17586 }
17587 assert_prod(case, "numeric", &numeric, expected_numeric(&numeric));
17588
17589 let mut timedeltas = Vec::with_capacity(len);
17590 timedeltas.push(Scalar::Timedelta64(case as i64 - 140));
17591 for _ in 1..len {
17592 let raw = (next(&mut seed) % 10_001) as i64 - 5_000;
17593 timedeltas.push(match next(&mut seed) % 7 {
17594 0 => Scalar::Null(NullKind::Null),
17595 1 => Scalar::Timedelta64(i64::MIN),
17596 _ => Scalar::Timedelta64(raw),
17597 });
17598 }
17599 assert_prod(
17600 case,
17601 "timedelta",
17602 &timedeltas,
17603 expected_timedelta(&timedeltas),
17604 );
17605 }
17606 }
17607
17608 #[test]
17609 fn nanskew_symmetric_distribution_near_zero() {
17610 let values = vec![
17611 Scalar::Float64(1.0),
17612 Scalar::Float64(2.0),
17613 Scalar::Float64(3.0),
17614 Scalar::Float64(4.0),
17615 Scalar::Float64(5.0),
17616 ];
17617 let skew = super::nanskew(&values);
17619 assert!(matches!(skew, Scalar::Float64(_)));
17620 let Scalar::Float64(v) = skew else {
17621 return;
17622 };
17623 assert!(v.abs() < 1e-9);
17624 }
17625
17626 #[test]
17627 fn nanskew_too_few_values_returns_null() {
17628 assert!(super::nanskew(&[]).is_missing());
17629 assert!(super::nanskew(&[Scalar::Float64(1.0), Scalar::Float64(2.0)]).is_missing());
17630 }
17631
17632 #[test]
17633 fn nankurt_symmetric_uniform_distribution() {
17634 let values = vec![
17635 Scalar::Float64(1.0),
17636 Scalar::Float64(2.0),
17637 Scalar::Float64(3.0),
17638 Scalar::Float64(4.0),
17639 Scalar::Float64(5.0),
17640 ];
17641 let kurt = super::nankurt(&values);
17643 assert!(matches!(kurt, Scalar::Float64(_)));
17644 let Scalar::Float64(v) = kurt else {
17645 return;
17646 };
17647 assert!((v + 1.2).abs() < 1e-9);
17648 }
17649
17650 #[test]
17651 fn nankurt_too_few_values_returns_null() {
17652 let vals: Vec<Scalar> = (0..3).map(|i| Scalar::Float64(i as f64)).collect();
17653 assert!(super::nankurt(&vals).is_missing());
17654 }
17655
17656 #[test]
17657 fn nanskew_constant_series_returns_zero() {
17658 let values = vec![
17659 Scalar::Float64(5.0),
17660 Scalar::Float64(5.0),
17661 Scalar::Float64(5.0),
17662 ];
17663 assert_eq!(super::nanskew(&values), Scalar::Float64(0.0));
17664 assert_eq!(
17665 super::nankurt(&[
17666 Scalar::Float64(5.0),
17667 Scalar::Float64(5.0),
17668 Scalar::Float64(5.0),
17669 Scalar::Float64(5.0),
17670 ]),
17671 Scalar::Float64(0.0)
17672 );
17673 }
17674
17675 #[test]
17676 fn nanskew_nankurt_match_numeric_oracle_jr7zk() {
17677 fn next(seed: &mut u64) -> u64 {
17680 *seed = seed
17681 .wrapping_mul(2862933555777941757)
17682 .wrapping_add(3037000493);
17683 *seed
17684 }
17685
17686 fn samples(values: &[Scalar]) -> Vec<f64> {
17687 values
17688 .iter()
17689 .filter(|value| !value.is_missing())
17690 .filter_map(|value| value.to_f64().ok())
17691 .collect()
17692 }
17693
17694 fn expected_skew(values: &[Scalar]) -> Scalar {
17695 let samples = samples(values);
17696 let n = samples.len() as f64;
17697 if n < 3.0 {
17698 return Scalar::Null(NullKind::NaN);
17699 }
17700 let mean = samples.iter().sum::<f64>() / n;
17701 let m2 = samples
17702 .iter()
17703 .map(|value| (value - mean).powi(2))
17704 .sum::<f64>();
17705 let m3 = samples
17706 .iter()
17707 .map(|value| (value - mean).powi(3))
17708 .sum::<f64>();
17709 let s2 = m2 / (n - 1.0);
17710 if s2 == 0.0 {
17711 return Scalar::Float64(0.0);
17712 }
17713 Scalar::Float64((n / ((n - 1.0) * (n - 2.0))) * (m3 / s2.powf(1.5)))
17714 }
17715
17716 fn expected_kurt(values: &[Scalar]) -> Scalar {
17717 let samples = samples(values);
17718 let n = samples.len() as f64;
17719 if n < 4.0 {
17720 return Scalar::Null(NullKind::NaN);
17721 }
17722 let mean = samples.iter().sum::<f64>() / n;
17723 let m2 = samples
17724 .iter()
17725 .map(|value| (value - mean).powi(2))
17726 .sum::<f64>();
17727 let m4 = samples
17728 .iter()
17729 .map(|value| (value - mean).powi(4))
17730 .sum::<f64>();
17731 let s2 = m2 / (n - 1.0);
17732 if s2 == 0.0 {
17733 return Scalar::Float64(0.0);
17734 }
17735 let adj = (n * (n + 1.0)) / ((n - 1.0) * (n - 2.0) * (n - 3.0));
17736 let sub = (3.0 * (n - 1.0).powi(2)) / ((n - 2.0) * (n - 3.0));
17737 Scalar::Float64(adj * (m4 / (s2 * s2)) - sub)
17738 }
17739
17740 fn assert_moments(case: usize, values: &[Scalar]) {
17741 let expected_skew = expected_skew(values);
17742 let expected_kurt = expected_kurt(values);
17743 let actual_skew = super::nanskew(values);
17744 let actual_kurt = super::nankurt(values);
17745 assert!(
17746 actual_skew.semantic_eq(&expected_skew),
17747 "case={case}: expected skew {expected_skew:?}, got {actual_skew:?} for {values:?}"
17748 );
17749 assert!(
17750 actual_kurt.semantic_eq(&expected_kurt),
17751 "case={case}: expected kurt {expected_kurt:?}, got {actual_kurt:?} for {values:?}"
17752 );
17753 }
17754
17755 assert_moments(
17756 usize::MAX,
17757 &[Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)],
17758 );
17759 assert_moments(
17760 usize::MAX - 1,
17761 &[
17762 Scalar::Float64(7.0),
17763 Scalar::Float64(7.0),
17764 Scalar::Float64(7.0),
17765 Scalar::Float64(7.0),
17766 ],
17767 );
17768
17769 let mut seed = 0x5ce7_9a55_a11c_0de5_u64;
17770 for case in 0..260 {
17771 let len = (next(&mut seed) % 89 + 1) as usize;
17772 let mut values = Vec::with_capacity(len);
17773 if case % 11 == 0 {
17774 values.extend((0..len).map(|_| Scalar::Float64(3.0)));
17775 } else {
17776 values.push(Scalar::Float64(case as f64 / 19.0));
17777 for _ in 1..len {
17778 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
17779 values.push(match next(&mut seed) % 8 {
17780 0 => Scalar::Null(NullKind::Null),
17781 1 => Scalar::Null(NullKind::NaN),
17782 2 => Scalar::Float64(f64::NAN),
17783 3 => Scalar::Bool(raw & 1 == 0),
17784 4 => Scalar::Int64(raw % 251),
17785 5 => Scalar::Float64(raw as f64 / 83.0),
17786 6 => Scalar::Float64(0.0),
17787 _ => Scalar::Float64(-0.0),
17788 });
17789 }
17790 }
17791 assert_moments(case, &values);
17792 }
17793 }
17794
17795 #[test]
17798 fn interval_default_closed_is_right() {
17799 assert_eq!(IntervalClosed::default(), IntervalClosed::Right);
17800 }
17801
17802 #[test]
17803 fn interval_left_and_right_closed_helpers() {
17804 assert!(IntervalClosed::Left.left_closed());
17805 assert!(!IntervalClosed::Left.right_closed());
17806 assert!(!IntervalClosed::Right.left_closed());
17807 assert!(IntervalClosed::Right.right_closed());
17808 assert!(IntervalClosed::Both.left_closed());
17809 assert!(IntervalClosed::Both.right_closed());
17810 assert!(!IntervalClosed::Neither.left_closed());
17811 assert!(!IntervalClosed::Neither.right_closed());
17812 }
17813
17814 #[test]
17815 fn interval_display_matches_pandas_notation() {
17816 assert_eq!(
17817 Interval::new(0.0, 5.0, IntervalClosed::Right).to_string(),
17818 "(0.0, 5.0]"
17819 );
17820 assert_eq!(
17821 Interval::new(0.0, 5.0, IntervalClosed::Left).to_string(),
17822 "[0.0, 5.0)"
17823 );
17824 assert_eq!(
17825 Interval::new(0.0, 5.0, IntervalClosed::Both).to_string(),
17826 "[0.0, 5.0]"
17827 );
17828 assert_eq!(
17829 Interval::new(0.0, 5.0, IntervalClosed::Neither).to_string(),
17830 "(0.0, 5.0)"
17831 );
17832 assert_eq!(
17833 Interval::new(2.5, 3.5, IntervalClosed::Right).to_string(),
17834 "(2.5, 3.5]"
17835 );
17836 assert_eq!(
17837 Interval::new(-1.0, 0.0, IntervalClosed::Right).to_string(),
17838 "(-1.0, 0.0]"
17839 );
17840 assert_eq!(
17841 Interval::new(1e20, 2e20, IntervalClosed::Right).to_string(),
17842 "(1e+20, 2e+20]"
17843 );
17844 }
17845
17846 #[test]
17847 fn interval_length_and_mid() {
17848 let i = Interval::new(2.0, 10.0, IntervalClosed::Right);
17849 assert_eq!(i.length(), 8.0);
17850 assert_eq!(i.mid(), 6.0);
17851 }
17852
17853 #[test]
17854 fn interval_contains_matches_closed_policy() {
17855 let right = Interval::new(0.0, 5.0, IntervalClosed::Right);
17856 assert!(!right.contains(0.0));
17857 assert!(right.contains(2.5));
17858 assert!(right.contains(5.0));
17859
17860 let left = Interval::new(0.0, 5.0, IntervalClosed::Left);
17861 assert!(left.contains(0.0));
17862 assert!(left.contains(2.5));
17863 assert!(!left.contains(5.0));
17864
17865 let both = Interval::new(0.0, 5.0, IntervalClosed::Both);
17866 assert!(both.contains(0.0));
17867 assert!(both.contains(5.0));
17868
17869 let neither = Interval::new(0.0, 5.0, IntervalClosed::Neither);
17870 assert!(!neither.contains(0.0));
17871 assert!(!neither.contains(5.0));
17872 assert!(neither.contains(2.5));
17873 }
17874
17875 #[test]
17876 fn interval_contains_nan_returns_false() {
17877 let i = Interval::new(0.0, 10.0, IntervalClosed::Both);
17878 assert!(!i.contains(f64::NAN));
17879 }
17880
17881 #[test]
17882 fn interval_is_empty_matches_pandas() {
17883 assert!(Interval::new(3.0, 3.0, IntervalClosed::Right).is_empty());
17885 assert!(Interval::new(3.0, 3.0, IntervalClosed::Left).is_empty());
17886 assert!(Interval::new(3.0, 3.0, IntervalClosed::Neither).is_empty());
17887 assert!(!Interval::new(3.0, 3.0, IntervalClosed::Both).is_empty());
17889 assert!(!Interval::new(0.0, 5.0, IntervalClosed::Right).is_empty());
17891 }
17892
17893 #[test]
17894 fn interval_overlaps_disjoint_returns_false() {
17895 let a = Interval::new(0.0, 1.0, IntervalClosed::Right);
17896 let b = Interval::new(2.0, 3.0, IntervalClosed::Right);
17897 assert!(!a.overlaps(&b));
17898 assert!(!b.overlaps(&a));
17899 }
17900
17901 #[test]
17902 fn interval_overlaps_nested_returns_true() {
17903 let outer = Interval::new(0.0, 10.0, IntervalClosed::Right);
17904 let inner = Interval::new(3.0, 7.0, IntervalClosed::Right);
17905 assert!(outer.overlaps(&inner));
17906 assert!(inner.overlaps(&outer));
17907 }
17908
17909 #[test]
17910 fn interval_overlaps_touching_respects_closed_policy() {
17911 let right_right = (
17913 Interval::new(0.0, 1.0, IntervalClosed::Right),
17914 Interval::new(1.0, 2.0, IntervalClosed::Right),
17915 );
17916 assert!(!right_right.0.overlaps(&right_right.1));
17918
17919 let both_both = (
17921 Interval::new(0.0, 1.0, IntervalClosed::Both),
17922 Interval::new(1.0, 2.0, IntervalClosed::Both),
17923 );
17924 assert!(both_both.0.overlaps(&both_both.1));
17925 }
17926
17927 #[test]
17928 fn interval_roundtrips_through_serde_json() {
17929 let i = Interval::new(1.5, 3.25, IntervalClosed::Both);
17930 let json = serde_json::to_string(&i).expect("serialize");
17931 let back: Interval = serde_json::from_str(&json).expect("deserialize");
17932 assert_eq!(i, back);
17933 }
17934
17935 #[test]
17936 fn interval_serde_default_closed_is_right_when_missing() {
17937 let back: Interval =
17939 serde_json::from_str(r#"{"left":0.0,"right":5.0}"#).expect("deserialize");
17940 assert_eq!(back.closed, IntervalClosed::Right);
17941 }
17942
17943 #[test]
17946 fn period_freq_parses_canonical_aliases() {
17947 assert_eq!(PeriodFreq::parse("A"), Some(PeriodFreq::ANNUAL));
17948 assert_eq!(PeriodFreq::parse("Y"), Some(PeriodFreq::ANNUAL));
17949 assert_eq!(PeriodFreq::parse("Q"), Some(PeriodFreq::QUARTERLY));
17950 assert_eq!(PeriodFreq::parse("M"), Some(PeriodFreq::Monthly));
17951 assert_eq!(PeriodFreq::parse("W"), Some(PeriodFreq::WEEKLY));
17952 assert_eq!(PeriodFreq::parse("D"), Some(PeriodFreq::Daily));
17953 assert_eq!(PeriodFreq::parse("B"), Some(PeriodFreq::Business));
17954 assert_eq!(PeriodFreq::parse("H"), Some(PeriodFreq::Hourly));
17955 assert_eq!(PeriodFreq::parse("T"), Some(PeriodFreq::Minutely));
17956 assert_eq!(PeriodFreq::parse("min"), Some(PeriodFreq::Minutely));
17957 assert_eq!(PeriodFreq::parse("S"), Some(PeriodFreq::Secondly));
17958 }
17959
17960 #[test]
17961 fn period_freq_parse_is_case_insensitive() {
17962 assert_eq!(PeriodFreq::parse("quarterly"), Some(PeriodFreq::QUARTERLY));
17963 assert_eq!(PeriodFreq::parse("MONTHLY"), Some(PeriodFreq::Monthly));
17964 }
17965
17966 #[test]
17967 fn period_freq_rejects_unknown_aliases() {
17968 assert_eq!(PeriodFreq::parse("nanosec"), None);
17969 assert_eq!(PeriodFreq::parse(""), None);
17970 assert_eq!(PeriodFreq::parse("xyz"), None);
17971 }
17972
17973 #[test]
17974 fn period_freq_alias_roundtrip() {
17975 for freq in [
17976 PeriodFreq::ANNUAL,
17977 PeriodFreq::QUARTERLY,
17978 PeriodFreq::Monthly,
17979 PeriodFreq::WEEKLY,
17980 PeriodFreq::Daily,
17981 PeriodFreq::Business,
17982 PeriodFreq::Hourly,
17983 PeriodFreq::Minutely,
17984 PeriodFreq::Secondly,
17985 PeriodFreq::Milliseconds,
17986 PeriodFreq::Microseconds,
17987 PeriodFreq::Nanoseconds,
17988 ] {
17989 assert_eq!(PeriodFreq::parse(freq.alias()), Some(freq));
17990 }
17991 }
17992
17993 #[test]
17998 fn anchored_period_freqs_parse_print_and_shift_39h5n() {
17999 for month in 1..=12_u8 {
18000 for freq in [PeriodFreq::Annual(month), PeriodFreq::Quarterly(month)] {
18001 assert_eq!(PeriodFreq::parse(freq.alias()), Some(freq));
18002 }
18003 }
18004 for day in 0..7_u8 {
18005 assert_eq!(
18006 PeriodFreq::parse(PeriodFreq::Weekly(day).alias()),
18007 Some(PeriodFreq::Weekly(day))
18008 );
18009 }
18010 assert_eq!(PeriodFreq::parse("Y-JUN"), Some(PeriodFreq::Annual(6)));
18011 assert_eq!(PeriodFreq::parse("A-JUN"), Some(PeriodFreq::Annual(6)));
18012 assert_eq!(PeriodFreq::parse("q-jan"), Some(PeriodFreq::Quarterly(1)));
18013 assert_eq!(PeriodFreq::parse("W-MON"), Some(PeriodFreq::Weekly(0)));
18014 assert_eq!(PeriodFreq::parse("Q-DEC"), Some(PeriodFreq::QUARTERLY));
18015 assert_eq!(PeriodFreq::parse("Q-XYZ"), None);
18017 assert_eq!(PeriodFreq::parse("M-JAN"), None);
18018 assert_eq!(PeriodFreq::parse("W-JAN"), None);
18019 assert_eq!(PeriodFreq::Annual(6).fiscal_month_shift(), 6);
18020 assert_eq!(PeriodFreq::Quarterly(1).fiscal_month_shift(), 11);
18021 assert_eq!(PeriodFreq::QUARTERLY.fiscal_month_shift(), 0);
18022 assert_eq!(PeriodFreq::Weekly(0).week_start_shift(), 1);
18023 assert_eq!(PeriodFreq::WEEKLY.week_start_shift(), 0);
18024 assert_eq!(
18025 Period::new(2827, PeriodFreq::Weekly(0)).to_string(),
18026 "2024-02-27/2024-03-04"
18027 );
18028 assert_eq!(
18029 Period::new(2826, PeriodFreq::Weekly(5)).to_string(),
18030 "2024-02-25/2024-03-02"
18031 );
18032 assert_eq!(
18033 Period::new(220, PeriodFreq::Quarterly(1)).to_string(),
18034 "2025Q1"
18035 );
18036 }
18037
18038 #[test]
18042 fn period_freq_subsecond_units_match_pandas() {
18043 assert_eq!(PeriodFreq::Milliseconds.alias(), "ms");
18045 assert_eq!(PeriodFreq::Microseconds.alias(), "us");
18046 assert_eq!(PeriodFreq::Nanoseconds.alias(), "ns");
18047 assert_eq!(PeriodFreq::Milliseconds.resolution(), Some("millisecond"));
18048 assert_eq!(PeriodFreq::Microseconds.resolution(), Some("microsecond"));
18049 assert_eq!(PeriodFreq::Nanoseconds.resolution(), Some("nanosecond"));
18050
18051 assert_eq!(PeriodFreq::parse("ms"), Some(PeriodFreq::Milliseconds));
18054 assert_eq!(PeriodFreq::parse("Ms"), Some(PeriodFreq::Milliseconds));
18055 assert_eq!(PeriodFreq::parse("mS"), Some(PeriodFreq::Milliseconds));
18056 assert_eq!(PeriodFreq::parse("MS"), None);
18057 assert_eq!(PeriodFreq::parse("us"), Some(PeriodFreq::Microseconds));
18059 assert_eq!(PeriodFreq::parse("US"), Some(PeriodFreq::Microseconds));
18060 assert_eq!(PeriodFreq::parse("ns"), Some(PeriodFreq::Nanoseconds));
18061 assert_eq!(PeriodFreq::parse("NS"), Some(PeriodFreq::Nanoseconds));
18062
18063 assert_eq!(
18066 Period::new(1_710_498_645_123, PeriodFreq::Milliseconds).calendar_string(),
18067 "2024-03-15 10:30:45.123"
18068 );
18069 assert_eq!(
18070 Period::new(1_710_498_645_123_456, PeriodFreq::Microseconds).calendar_string(),
18071 "2024-03-15 10:30:45.123456"
18072 );
18073 assert_eq!(
18074 Period::new(1_710_498_645_123_456_789, PeriodFreq::Nanoseconds).calendar_string(),
18075 "2024-03-15 10:30:45.123456789"
18076 );
18077
18078 assert_eq!(
18082 Period::new(0, PeriodFreq::Milliseconds).calendar_string(),
18083 "1970-01-01 00:00:00.000"
18084 );
18085 assert_eq!(
18086 Period::new(-1, PeriodFreq::Milliseconds).calendar_string(),
18087 "1969-12-31 23:59:59.999"
18088 );
18089 assert_eq!(
18090 Period::new(-1_000, PeriodFreq::Microseconds).calendar_string(),
18091 "1969-12-31 23:59:59.999000"
18092 );
18093 assert_eq!(
18094 Period::new(-999_999, PeriodFreq::Nanoseconds).calendar_string(),
18095 "1969-12-31 23:59:59.999000001"
18096 );
18097 }
18098
18099 #[test]
18100 fn period_freq_anchored_aliases_are_pandas_canonical_h2wiv() {
18101 assert_eq!(PeriodFreq::ANNUAL.alias(), "Y-DEC");
18102 assert_eq!(PeriodFreq::QUARTERLY.alias(), "Q-DEC");
18103 assert_eq!(PeriodFreq::WEEKLY.alias(), "W-SUN");
18104
18105 assert_eq!(PeriodFreq::parse("A"), Some(PeriodFreq::ANNUAL));
18106 assert_eq!(PeriodFreq::parse("Y"), Some(PeriodFreq::ANNUAL));
18107 assert_eq!(PeriodFreq::parse("Y-DEC"), Some(PeriodFreq::ANNUAL));
18108 assert_eq!(PeriodFreq::parse("Q"), Some(PeriodFreq::QUARTERLY));
18109 assert_eq!(PeriodFreq::parse("Q-DEC"), Some(PeriodFreq::QUARTERLY));
18110 assert_eq!(PeriodFreq::parse("W"), Some(PeriodFreq::WEEKLY));
18111 assert_eq!(PeriodFreq::parse("W-SUN"), Some(PeriodFreq::WEEKLY));
18112 }
18113
18114 #[test]
18115 fn period_freq_intraday_aliases_are_pandas_canonical_8kfdo() {
18116 assert_eq!(PeriodFreq::Hourly.alias(), "h");
18117 assert_eq!(PeriodFreq::Minutely.alias(), "min");
18118 assert_eq!(PeriodFreq::Secondly.alias(), "s");
18119
18120 assert_eq!(PeriodFreq::parse("H"), Some(PeriodFreq::Hourly));
18121 assert_eq!(PeriodFreq::parse("T"), Some(PeriodFreq::Minutely));
18122 assert_eq!(PeriodFreq::parse("S"), Some(PeriodFreq::Secondly));
18123 }
18124
18125 #[test]
18129 fn period_freq_resolution_is_the_component_word_not_the_alias() {
18130 assert_eq!(PeriodFreq::ANNUAL.resolution(), Some("year"));
18131 assert_eq!(PeriodFreq::QUARTERLY.resolution(), Some("quarter"));
18132 assert_eq!(PeriodFreq::Monthly.resolution(), Some("month"));
18133 assert_eq!(PeriodFreq::Daily.resolution(), Some("day"));
18134 assert_eq!(PeriodFreq::Hourly.resolution(), Some("hour"));
18135 assert_eq!(PeriodFreq::Minutely.resolution(), Some("minute"));
18136 assert_eq!(PeriodFreq::Secondly.resolution(), Some("second"));
18137
18138 assert_eq!(PeriodFreq::WEEKLY.resolution(), None);
18140 assert_eq!(PeriodFreq::Business.resolution(), None);
18141
18142 for freq in [
18147 PeriodFreq::ANNUAL,
18148 PeriodFreq::QUARTERLY,
18149 PeriodFreq::Monthly,
18150 PeriodFreq::WEEKLY,
18151 PeriodFreq::Daily,
18152 PeriodFreq::Business,
18153 PeriodFreq::Hourly,
18154 PeriodFreq::Minutely,
18155 PeriodFreq::Secondly,
18156 ] {
18157 assert_ne!(
18158 Some(freq.alias()),
18159 freq.resolution(),
18160 "{freq:?} reports its alias as its resolution again"
18161 );
18162 }
18163 }
18164
18165 #[test]
18166 fn period_scalar_accessors_match_pandas_star8() {
18167 let period = Period::new(600, PeriodFreq::Monthly);
18168
18169 assert_eq!(period.ordinal(), 600);
18170 assert_eq!(period.freq(), PeriodFreq::Monthly);
18171 assert_eq!(period.freqstr(), "M");
18172 }
18173
18174 #[test]
18175 fn period_parse_common_pandas_ordinals_avm08() {
18176 assert_eq!(
18177 Period::parse("2024").unwrap(),
18178 Period::new(54, PeriodFreq::ANNUAL)
18179 );
18180 assert_eq!(
18181 Period::parse("2024Q1").unwrap(),
18182 Period::new(216, PeriodFreq::QUARTERLY)
18183 );
18184 assert_eq!(
18185 Period::parse("2024-01").unwrap(),
18186 Period::new(648, PeriodFreq::Monthly)
18187 );
18188 assert_eq!(
18189 Period::parse("2024-01-15").unwrap(),
18190 Period::new(19_737, PeriodFreq::Daily)
18191 );
18192 assert!(Period::parse("216").is_err());
18193 }
18194
18195 #[test]
18196 fn period_shift_advances_ordinal() {
18197 let q1 = Period::new(216, PeriodFreq::QUARTERLY);
18198 let q2 = q1.shift(1);
18199 assert_eq!(q2.ordinal, 217);
18200 assert_eq!(q2.freq, PeriodFreq::QUARTERLY);
18201 let q0 = q1.shift(-1);
18202 assert_eq!(q0.ordinal, 215);
18203 }
18204
18205 #[test]
18206 fn period_shift_saturates_on_overflow() {
18207 let p = Period::new(i64::MAX - 2, PeriodFreq::Daily);
18208 assert_eq!(p.shift(100).ordinal, i64::MAX);
18209 let p = Period::new(i64::MIN + 2, PeriodFreq::Daily);
18210 assert_eq!(p.shift(-100).ordinal, i64::MIN);
18211 }
18212
18213 #[test]
18214 fn period_diff_returns_period_count() {
18215 let a = Period::new(216, PeriodFreq::QUARTERLY);
18216 let b = Period::new(220, PeriodFreq::QUARTERLY);
18217 assert_eq!(b.diff(&a), Some(4));
18218 assert_eq!(a.diff(&b), Some(-4));
18219 }
18220
18221 #[test]
18222 fn period_diff_rejects_mismatched_freq() {
18223 let monthly = Period::new(100, PeriodFreq::Monthly);
18224 let quarterly = Period::new(100, PeriodFreq::QUARTERLY);
18225 assert_eq!(monthly.diff(&quarterly), None);
18226 assert_eq!(quarterly.diff(&monthly), None);
18227 }
18228
18229 #[test]
18230 fn period_cmp_same_freq_respects_ordinal_order() {
18231 use std::cmp::Ordering;
18232 let a = Period::new(10, PeriodFreq::Monthly);
18233 let b = Period::new(20, PeriodFreq::Monthly);
18234 assert_eq!(a.cmp_same_freq(&b), Some(Ordering::Less));
18235 assert_eq!(b.cmp_same_freq(&a), Some(Ordering::Greater));
18236 assert_eq!(a.cmp_same_freq(&a), Some(Ordering::Equal));
18237 }
18238
18239 #[test]
18240 fn period_cmp_cross_freq_returns_none() {
18241 let m = Period::new(1, PeriodFreq::Monthly);
18242 let q = Period::new(1, PeriodFreq::QUARTERLY);
18243 assert_eq!(m.cmp_same_freq(&q), None);
18244 }
18245
18246 #[test]
18247 fn period_arithmetic_matches_seeded_oracles_bac28() {
18248 use std::cmp::Ordering;
18249
18250 fn next(seed: &mut u64) -> u64 {
18251 *seed = seed
18252 .wrapping_mul(2862933555777941757)
18253 .wrapping_add(3037000493);
18254 *seed
18255 }
18256
18257 fn freq_for(raw: u64) -> PeriodFreq {
18258 match raw % 12 {
18261 0 => PeriodFreq::ANNUAL,
18262 1 => PeriodFreq::QUARTERLY,
18263 2 => PeriodFreq::Monthly,
18264 3 => PeriodFreq::WEEKLY,
18265 4 => PeriodFreq::Daily,
18266 5 => PeriodFreq::Business,
18267 6 => PeriodFreq::Hourly,
18268 7 => PeriodFreq::Minutely,
18269 8 => PeriodFreq::Secondly,
18270 9 => PeriodFreq::Milliseconds,
18271 10 => PeriodFreq::Microseconds,
18272 _ => PeriodFreq::Nanoseconds,
18273 }
18274 }
18275
18276 fn different_freq(freq: PeriodFreq) -> PeriodFreq {
18277 match freq {
18278 PeriodFreq::Annual(_) => PeriodFreq::QUARTERLY,
18279 PeriodFreq::Quarterly(_) => PeriodFreq::Monthly,
18280 PeriodFreq::Monthly => PeriodFreq::WEEKLY,
18281 PeriodFreq::Weekly(_) => PeriodFreq::Daily,
18282 PeriodFreq::Daily => PeriodFreq::Business,
18283 PeriodFreq::Business => PeriodFreq::Hourly,
18284 PeriodFreq::Hourly => PeriodFreq::Minutely,
18285 PeriodFreq::Minutely => PeriodFreq::Secondly,
18286 PeriodFreq::Secondly => PeriodFreq::Milliseconds,
18290 PeriodFreq::Milliseconds => PeriodFreq::Microseconds,
18291 PeriodFreq::Microseconds => PeriodFreq::Nanoseconds,
18292 PeriodFreq::Nanoseconds => PeriodFreq::ANNUAL,
18293 }
18294 }
18295
18296 fn assert_period_case(
18297 case: usize,
18298 freq: PeriodFreq,
18299 ordinal: i64,
18300 shift_by: i64,
18301 other_ordinal: i64,
18302 ) {
18303 let period = Period::new(ordinal, freq);
18304 let shifted = period.shift(shift_by);
18305 assert_eq!(
18306 shifted.ordinal,
18307 ordinal.saturating_add(shift_by),
18308 "case {case}: shift ordinal"
18309 );
18310 assert_eq!(shifted.freq, freq, "case {case}: shift freq");
18311
18312 let same_freq_other = Period::new(other_ordinal, freq);
18313 assert_eq!(
18314 period.diff(&same_freq_other),
18315 Some(ordinal.saturating_sub(other_ordinal)),
18316 "case {case}: same-freq diff"
18317 );
18318 assert_eq!(
18319 period.cmp_same_freq(&same_freq_other),
18320 Some(ordinal.cmp(&other_ordinal)),
18321 "case {case}: same-freq cmp"
18322 );
18323
18324 let cross_freq_other = Period::new(other_ordinal, different_freq(freq));
18325 assert_eq!(
18326 period.diff(&cross_freq_other),
18327 None,
18328 "case {case}: cross-freq diff"
18329 );
18330 assert_eq!(
18331 period.cmp_same_freq(&cross_freq_other),
18332 None,
18333 "case {case}: cross-freq cmp"
18334 );
18335 }
18336
18337 assert_period_case(usize::MAX, PeriodFreq::Daily, i64::MAX - 2, 10, i64::MIN);
18338 assert_period_case(
18339 usize::MAX - 1,
18340 PeriodFreq::Daily,
18341 i64::MIN + 2,
18342 -10,
18343 i64::MAX,
18344 );
18345 assert_eq!(
18346 Period::new(10, PeriodFreq::Monthly)
18347 .cmp_same_freq(&Period::new(10, PeriodFreq::Monthly)),
18348 Some(Ordering::Equal)
18349 );
18350
18351 let mut seed = 0xbac2_8d1f_0d1c_5eed_u64;
18352 for case in 0..260 {
18353 let freq = freq_for(next(&mut seed));
18354 let ordinal = match case % 53 {
18355 0 => i64::MAX - (next(&mut seed) % 8) as i64,
18356 1 => i64::MIN + (next(&mut seed) % 8) as i64,
18357 _ => (next(&mut seed) % 200_001) as i64 - 100_000,
18358 };
18359 let shift_by = match case % 47 {
18360 0 => 512,
18361 1 => -512,
18362 _ => (next(&mut seed) % 4097) as i64 - 2048,
18363 };
18364 let other_ordinal = match case % 41 {
18365 0 => i64::MAX,
18366 1 => i64::MIN,
18367 _ => (next(&mut seed) % 200_001) as i64 - 100_000,
18368 };
18369 assert_period_case(case, freq, ordinal, shift_by, other_ordinal);
18370 }
18371 }
18372
18373 #[test]
18374 fn period_display_is_pandas_calendar_string() {
18375 assert_eq!(
18377 Period::new(216, PeriodFreq::QUARTERLY).to_string(),
18378 "2024Q1"
18379 );
18380 assert_eq!(Period::new(54, PeriodFreq::ANNUAL).to_string(), "2024");
18382 assert_eq!(Period::new(650, PeriodFreq::Monthly).to_string(), "2024-03");
18384 assert_eq!(
18386 Period::new(fp_days("2024-01-15"), PeriodFreq::Daily).to_string(),
18387 "2024-01-15"
18388 );
18389 assert_eq!(
18390 Scalar::Period(Period::new(i64::MIN, PeriodFreq::Daily)).to_string(),
18391 "NaT"
18392 );
18393 }
18394
18395 #[test]
18403 fn weekly_and_business_periods_do_not_index_days() {
18404 for (ordinal, want) in [
18409 (0_i64, "1969-12-22/1969-12-28"),
18410 (1, "1969-12-29/1970-01-04"),
18411 (2829, "2024-03-11/2024-03-17"),
18412 (1540, "1999-06-28/1999-07-04"),
18413 (15237, "2261-12-30/2262-01-05"),
18414 (-1, "1969-12-15/1969-12-21"),
18416 (-2829, "1915-10-04/1915-10-10"),
18417 ] {
18418 assert_eq!(
18419 Period::new(ordinal, PeriodFreq::WEEKLY).to_string(),
18420 want,
18421 "weekly ordinal {ordinal}"
18422 );
18423 }
18424
18425 for (ordinal, want) in [
18429 (0_i64, "1970-01-01"), (1, "1970-01-02"), (2, "1970-01-05"), (3, "1970-01-06"),
18433 (4, "1970-01-07"),
18434 (5, "1970-01-08"),
18435 (14141, "2024-03-15"),
18436 (76179, "2262-01-01"),
18437 (7697, "1999-07-05"),
18440 (-1, "1969-12-31"),
18441 (-5, "1969-12-25"),
18442 (-6, "1969-12-24"),
18443 ] {
18444 assert_eq!(
18445 Period::new(ordinal, PeriodFreq::Business).to_string(),
18446 want,
18447 "business ordinal {ordinal}"
18448 );
18449 }
18450
18451 for ordinal in -400_i64..400 {
18455 let rendered = Period::new(ordinal, PeriodFreq::Business).to_string();
18456 let later = Period::new(ordinal + 5, PeriodFreq::Business).to_string();
18457 assert_ne!(rendered, later, "business ordinals must not repeat");
18458 }
18459
18460 assert_eq!(Period::new(i64::MIN, PeriodFreq::WEEKLY).to_string(), "NaT");
18461 assert_eq!(
18462 Period::new(i64::MIN, PeriodFreq::Business).to_string(),
18463 "NaT"
18464 );
18465 }
18466
18467 fn period_display_former_profile(period: &Period) -> String {
18468 let calendar = period.calendar_string();
18469 let mut rendered = String::new();
18470 rendered.push_str(&calendar);
18471 rendered
18472 }
18473
18474 fn measure_period_renderer(periods: &[Period], render: impl Fn(&Period) -> String) -> u128 {
18475 use std::{hint::black_box, time::Instant};
18476
18477 let started = Instant::now();
18478 let mut checksum = 0usize;
18479 for period in periods {
18480 let rendered = render(black_box(period));
18481 checksum = checksum.wrapping_add(rendered.len());
18482 drop(black_box(rendered));
18483 }
18484 black_box(checksum);
18485 started.elapsed().as_nanos()
18486 }
18487
18488 #[test]
18489 #[ignore = "release-only attribution probe for br-frankenpandas-6pqra"]
18490 fn profile_period_display_direct_sink_ab_6pqra() {
18491 const FREQUENCIES: [PeriodFreq; 9] = [
18492 PeriodFreq::ANNUAL,
18493 PeriodFreq::QUARTERLY,
18494 PeriodFreq::Monthly,
18495 PeriodFreq::WEEKLY,
18496 PeriodFreq::Daily,
18497 PeriodFreq::Business,
18498 PeriodFreq::Hourly,
18499 PeriodFreq::Minutely,
18500 PeriodFreq::Secondly,
18501 ];
18502 const SAMPLES: usize = 10;
18503
18504 let periods = (0..65_536)
18505 .map(|index| {
18506 let ordinal = if index % 4093 == 0 {
18507 i64::MIN
18508 } else {
18509 ((index as i64 * 7_919) % 4_000_001) - 2_000_000
18510 };
18511 Period::new(ordinal, FREQUENCIES[index % FREQUENCIES.len()])
18512 })
18513 .collect::<Vec<_>>();
18514
18515 for period in &periods {
18516 assert_eq!(period_display_former_profile(period), period.to_string());
18517 }
18518
18519 for _ in 0..2 {
18520 measure_period_renderer(&periods, period_display_former_profile);
18521 measure_period_renderer(&periods, Period::to_string);
18522 }
18523
18524 let mut former_ns = Vec::with_capacity(SAMPLES);
18525 let mut public_ns = Vec::with_capacity(SAMPLES);
18526 for sample in 0..SAMPLES {
18527 if sample % 2 == 0 {
18528 former_ns.push(measure_period_renderer(
18529 &periods,
18530 period_display_former_profile,
18531 ));
18532 public_ns.push(measure_period_renderer(&periods, Period::to_string));
18533 } else {
18534 public_ns.push(measure_period_renderer(&periods, Period::to_string));
18535 former_ns.push(measure_period_renderer(
18536 &periods,
18537 period_display_former_profile,
18538 ));
18539 }
18540 }
18541 former_ns.sort_unstable();
18542 public_ns.sort_unstable();
18543 let former_p50 = former_ns[SAMPLES / 2];
18544 let public_p50 = public_ns[SAMPLES / 2];
18545 let former_p95 = former_ns[SAMPLES - 1];
18546 let public_p95 = public_ns[SAMPLES - 1];
18547 println!("PROFILE_PERIOD_DISPLAY_FORMER_NS={former_ns:?}");
18548 println!("PROFILE_PERIOD_DISPLAY_PUBLIC_NS={public_ns:?}");
18549 println!(
18550 "PROFILE_PERIOD_DISPLAY_P50_RATIO={:.6}",
18551 former_p50 as f64 / public_p50 as f64
18552 );
18553 println!(
18554 "PROFILE_PERIOD_DISPLAY_P95_RATIO={:.6}",
18555 former_p95 as f64 / public_p95 as f64
18556 );
18557 }
18558
18559 #[cfg(test)]
18560 fn fp_days(ymd: &str) -> i64 {
18561 Period::parse(ymd).expect("daily period").ordinal
18562 }
18563
18564 #[test]
18565 fn period_roundtrips_through_serde_json() {
18566 let p = Period::new(42, PeriodFreq::WEEKLY);
18567 let json = serde_json::to_string(&p).expect("serialize");
18568 let back: Period = serde_json::from_str(&json).expect("deserialize");
18569 assert_eq!(p, back);
18570 }
18571
18572 use super::period_range;
18575
18576 #[test]
18577 fn period_range_zero_periods_is_empty() {
18578 let start = Period::new(216, PeriodFreq::QUARTERLY);
18579 assert!(period_range(start, 0).is_empty());
18580 }
18581
18582 #[test]
18583 fn period_range_single_period_returns_start_only() {
18584 let start = Period::new(216, PeriodFreq::QUARTERLY);
18585 let r = period_range(start, 1);
18586 assert_eq!(r.len(), 1);
18587 assert_eq!(r[0], start);
18588 }
18589
18590 #[test]
18591 fn period_range_increments_ordinal_by_one_per_step() {
18592 let start = Period::new(216, PeriodFreq::QUARTERLY);
18593 let r = period_range(start, 4);
18594 assert_eq!(r.len(), 4);
18595 assert_eq!(r[0].ordinal, 216);
18596 assert_eq!(r[1].ordinal, 217);
18597 assert_eq!(r[2].ordinal, 218);
18598 assert_eq!(r[3].ordinal, 219);
18599 }
18600
18601 #[test]
18602 fn period_range_preserves_frequency() {
18603 let start = Period::new(0, PeriodFreq::Monthly);
18604 let r = period_range(start, 12);
18605 assert!(r.iter().all(|p| p.freq == PeriodFreq::Monthly));
18606 }
18607
18608 #[test]
18609 fn period_range_negative_starting_ordinal_works() {
18610 let start = Period::new(-3, PeriodFreq::ANNUAL);
18612 let r = period_range(start, 5);
18613 assert_eq!(
18614 r.iter().map(|p| p.ordinal).collect::<Vec<_>>(),
18615 vec![-3, -2, -1, 0, 1]
18616 );
18617 }
18618
18619 #[test]
18620 fn period_range_large_n_does_not_panic() {
18621 let start = Period::new(0, PeriodFreq::Monthly);
18623 let r = period_range(start, 1024);
18624 assert_eq!(r.len(), 1024);
18625 assert_eq!(r[1023].ordinal, 1023);
18626 }
18627
18628 #[test]
18629 fn period_range_matches_seeded_ordinal_oracle_z3zh2() {
18630 fn next(seed: &mut u64) -> u64 {
18631 *seed = seed
18632 .wrapping_mul(6364136223846793005)
18633 .wrapping_add(1442695040888963407);
18634 *seed
18635 }
18636
18637 fn freq_for(raw: u64) -> PeriodFreq {
18638 match raw % 12 {
18641 0 => PeriodFreq::ANNUAL,
18642 1 => PeriodFreq::QUARTERLY,
18643 2 => PeriodFreq::Monthly,
18644 3 => PeriodFreq::WEEKLY,
18645 4 => PeriodFreq::Daily,
18646 5 => PeriodFreq::Business,
18647 6 => PeriodFreq::Hourly,
18648 7 => PeriodFreq::Minutely,
18649 8 => PeriodFreq::Secondly,
18650 9 => PeriodFreq::Milliseconds,
18651 10 => PeriodFreq::Microseconds,
18652 _ => PeriodFreq::Nanoseconds,
18653 }
18654 }
18655
18656 fn assert_oracle_case(case: usize, start: Period, periods: usize) {
18657 let got = period_range(start, periods);
18658 assert_eq!(got.len(), periods, "case {case}: length");
18659
18660 for (position, period) in got.iter().enumerate() {
18661 let expected_ordinal = start.ordinal.saturating_add(position as i64);
18662 assert_eq!(
18663 period.ordinal, expected_ordinal,
18664 "case {case}: ordinal at {position}"
18665 );
18666 assert_eq!(period.freq, start.freq, "case {case}: freq at {position}");
18667 }
18668 }
18669
18670 assert_oracle_case(usize::MAX, Period::new(42, PeriodFreq::Monthly), 0);
18671 assert_oracle_case(
18672 usize::MAX - 1,
18673 Period::new(i64::MAX - 3, PeriodFreq::Daily),
18674 8,
18675 );
18676
18677 let mut seed = 0x9e21_0d1c_5eed_0421_u64;
18678 for case in 0..260 {
18679 let freq = freq_for(next(&mut seed));
18680 let periods = (next(&mut seed) % 80) as usize;
18681 let start_ordinal = if case % 37 == 0 {
18682 i64::MAX - 7
18683 } else {
18684 (next(&mut seed) % 20_001) as i64 - 10_000
18685 };
18686 assert_oracle_case(case, Period::new(start_ordinal, freq), periods);
18687 }
18688 }
18689
18690 use super::{TypeError, interval_range, interval_range_by_periods, interval_range_by_step};
18693
18694 #[test]
18695 fn interval_range_by_periods_matches_pandas_default_case() {
18696 let bins = interval_range_by_periods(0.0, 10.0, 5, IntervalClosed::Right);
18698 assert_eq!(bins.len(), 5);
18699 for (i, bin) in bins.iter().enumerate() {
18700 assert_eq!(bin.left, (i as f64) * 2.0);
18701 assert_eq!(bin.right, ((i + 1) as f64) * 2.0);
18702 assert_eq!(bin.closed, IntervalClosed::Right);
18703 }
18704 }
18705
18706 #[test]
18707 fn interval_range_by_periods_final_edge_is_exact_end() {
18708 let bins = interval_range_by_periods(0.0, 1.0, 7, IntervalClosed::Right);
18710 assert_eq!(bins.last().unwrap().right, 1.0);
18711 }
18712
18713 #[test]
18714 fn interval_range_by_periods_zero_periods_is_empty() {
18715 assert!(interval_range_by_periods(0.0, 10.0, 0, IntervalClosed::Right).is_empty());
18716 }
18717
18718 #[test]
18719 fn interval_range_by_periods_reversed_range_is_empty() {
18720 assert!(interval_range_by_periods(10.0, 0.0, 5, IntervalClosed::Right).is_empty());
18722 }
18723
18724 #[test]
18725 fn interval_range_by_periods_preserves_closed_policy() {
18726 for closed in [
18727 IntervalClosed::Left,
18728 IntervalClosed::Right,
18729 IntervalClosed::Both,
18730 IntervalClosed::Neither,
18731 ] {
18732 let bins = interval_range_by_periods(0.0, 4.0, 2, closed);
18733 assert!(bins.iter().all(|b| b.closed == closed));
18734 }
18735 }
18736
18737 #[test]
18738 fn interval_range_by_step_matches_pandas_default_case() {
18739 let bins = interval_range_by_step(0.0, 10.0, 2.0, IntervalClosed::Right).expect("ok");
18741 assert_eq!(bins.len(), 5);
18742 assert_eq!(bins[0].left, 0.0);
18743 assert_eq!(bins[4].right, 10.0);
18744 }
18745
18746 #[test]
18747 fn interval_range_by_step_rejects_non_positive_step() {
18748 assert!(matches!(
18749 interval_range_by_step(0.0, 10.0, 0.0, IntervalClosed::Right),
18750 Err(TypeError::InvalidIntervalStep { .. })
18751 ));
18752 assert!(matches!(
18753 interval_range_by_step(0.0, 10.0, -2.0, IntervalClosed::Right),
18754 Err(TypeError::InvalidIntervalStep { .. })
18755 ));
18756 assert!(matches!(
18757 interval_range_by_step(0.0, 10.0, f64::NAN, IntervalClosed::Right),
18758 Err(TypeError::InvalidIntervalStep { .. })
18759 ));
18760 assert!(matches!(
18761 interval_range_by_step(0.0, 10.0, f64::INFINITY, IntervalClosed::Right),
18762 Err(TypeError::InvalidIntervalStep { .. })
18763 ));
18764 }
18765
18766 #[test]
18767 fn interval_range_by_step_rejects_non_dividing_step() {
18768 assert!(matches!(
18771 interval_range_by_step(0.0, 10.0, 3.0, IntervalClosed::Right),
18772 Err(TypeError::IntervalStepDoesNotDivide { .. })
18773 ));
18774 }
18775
18776 #[test]
18777 fn interval_range_by_step_reversed_range_is_empty() {
18778 let bins = interval_range_by_step(10.0, 0.0, 2.0, IntervalClosed::Right).expect("ok");
18779 assert!(bins.is_empty());
18780 }
18781
18782 #[test]
18783 fn interval_range_by_step_degenerate_zero_span_is_empty() {
18784 let bins = interval_range_by_step(5.0, 5.0, 1.0, IntervalClosed::Right).expect("ok");
18785 assert!(bins.is_empty());
18786 }
18787
18788 #[test]
18789 fn interval_range_by_step_accepts_float_step_within_tolerance() {
18790 let bins = interval_range_by_step(0.0, 1.0, 0.1, IntervalClosed::Right).expect("ok");
18792 assert_eq!(bins.len(), 10);
18793 assert_eq!(bins.last().unwrap().right, 1.0);
18794 }
18795
18796 #[test]
18797 fn interval_range_unified_api_tests() {
18798 let r1 = interval_range(Some(0.0), Some(10.0), Some(5), None, None).expect("ok");
18800 assert_eq!(r1.len(), 5);
18801 assert_eq!(r1[0].left, 0.0);
18802 assert_eq!(r1[0].right, 2.0);
18803 assert_eq!(r1[4].right, 10.0);
18804 assert_eq!(r1[0].closed, IntervalClosed::Right);
18805
18806 let r2 = interval_range(Some(0.0), Some(10.0), None, Some(2.0), None).expect("ok");
18808 assert_eq!(r2.len(), 5);
18809 assert_eq!(r2[0].left, 0.0);
18810 assert_eq!(r2[4].right, 10.0);
18811
18812 let r3 = interval_range(
18814 Some(0.0),
18815 None,
18816 Some(5),
18817 Some(2.0),
18818 Some(IntervalClosed::Both),
18819 )
18820 .expect("ok");
18821 assert_eq!(r3.len(), 5);
18822 assert_eq!(r3[0].left, 0.0);
18823 assert_eq!(r3[4].right, 10.0);
18824 assert_eq!(r3[0].closed, IntervalClosed::Both);
18825
18826 let r4 = interval_range(
18828 None,
18829 Some(10.0),
18830 Some(5),
18831 Some(2.0),
18832 Some(IntervalClosed::Left),
18833 )
18834 .expect("ok");
18835 assert_eq!(r4.len(), 5);
18836 assert_eq!(r4[0].left, 0.0);
18837 assert_eq!(r4[4].right, 10.0);
18838 assert_eq!(r4[0].closed, IntervalClosed::Left);
18839
18840 assert!(matches!(
18842 interval_range(None, None, None, None, None),
18843 Err(TypeError::IntervalRangeParameterCount)
18844 ));
18845 assert!(matches!(
18846 interval_range(Some(0.0), Some(10.0), None, None, None),
18847 Err(TypeError::IntervalRangeParameterCount)
18848 ));
18849 assert!(matches!(
18850 interval_range(Some(0.0), Some(10.0), Some(5), Some(2.0), None),
18851 Err(TypeError::IntervalRangeParameterCount)
18852 ));
18853
18854 assert!(matches!(
18856 interval_range(Some(0.0), None, Some(5), Some(-1.0), None),
18857 Err(TypeError::InvalidIntervalStep { .. })
18858 ));
18859 assert!(matches!(
18860 interval_range(Some(0.0), None, Some(5), Some(0.0), None),
18861 Err(TypeError::InvalidIntervalStep { .. })
18862 ));
18863 }
18864
18865 #[test]
18866 fn interval_range_matches_seeded_arithmetic_oracle_t9ozf() {
18867 fn next(seed: &mut u64) -> u64 {
18870 *seed = seed
18871 .wrapping_mul(2862933555777941757)
18872 .wrapping_add(3037000493);
18873 *seed
18874 }
18875
18876 fn closed_for(raw: u64) -> IntervalClosed {
18877 match raw % 4 {
18878 0 => IntervalClosed::Left,
18879 1 => IntervalClosed::Right,
18880 2 => IntervalClosed::Both,
18881 _ => IntervalClosed::Neither,
18882 }
18883 }
18884
18885 fn assert_interval(
18886 case: usize,
18887 kind: &str,
18888 pos: usize,
18889 actual: &Interval,
18890 expected: &Interval,
18891 ) {
18892 assert!(
18893 (actual.left - expected.left).abs() < 1e-12,
18894 "case={case} kind={kind} pos={pos}: expected left {}, got {}",
18895 expected.left,
18896 actual.left
18897 );
18898 assert!(
18899 (actual.right - expected.right).abs() < 1e-12,
18900 "case={case} kind={kind} pos={pos}: expected right {}, got {}",
18901 expected.right,
18902 actual.right
18903 );
18904 assert_eq!(
18905 actual.closed, expected.closed,
18906 "case={case} kind={kind} pos={pos}: closed mismatch"
18907 );
18908 }
18909
18910 fn expected_by_periods(
18911 start: f64,
18912 end: f64,
18913 periods: usize,
18914 closed: IntervalClosed,
18915 ) -> Vec<Interval> {
18916 if periods == 0 || !start.is_finite() || !end.is_finite() || start >= end {
18917 return Vec::new();
18918 }
18919 let step = (end - start) / periods as f64;
18920 (0..periods)
18921 .map(|pos| {
18922 let left = start + step * pos as f64;
18923 let right = if pos + 1 == periods {
18924 end
18925 } else {
18926 start + step * (pos + 1) as f64
18927 };
18928 Interval::new(left, right, closed)
18929 })
18930 .collect()
18931 }
18932
18933 fn expected_by_step(
18934 start: f64,
18935 end: f64,
18936 step: f64,
18937 closed: IntervalClosed,
18938 ) -> Vec<Interval> {
18939 if start >= end {
18940 return Vec::new();
18941 }
18942 let count = ((end - start) / step).round() as usize;
18943 (0..count)
18944 .map(|pos| {
18945 let left = start + step * pos as f64;
18946 let right = if pos + 1 == count {
18947 end
18948 } else {
18949 start + step * (pos + 1) as f64
18950 };
18951 Interval::new(left, right, closed)
18952 })
18953 .collect()
18954 }
18955
18956 assert!(interval_range_by_periods(5.0, 5.0, 4, IntervalClosed::Right).is_empty());
18957 assert!(interval_range_by_periods(5.0, 4.0, 4, IntervalClosed::Right).is_empty());
18958 assert!(
18959 interval_range_by_step(5.0, 5.0, 1.0, IntervalClosed::Right)
18960 .expect("zero span")
18961 .is_empty()
18962 );
18963
18964 let mut seed = 0x171e_7a11_c0de_5eed_u64;
18965 for case in 0..220 {
18966 let start = (next(&mut seed) % 2_001) as f64 / 10.0 - 100.0;
18967 let periods = (next(&mut seed) % 24 + 1) as usize;
18968 let width = (next(&mut seed) % 1_000 + 1) as f64 / 4.0;
18969 let end = start + width;
18970 let closed = closed_for(next(&mut seed));
18971
18972 let actual = interval_range_by_periods(start, end, periods, closed);
18973 let expected = expected_by_periods(start, end, periods, closed);
18974 assert_eq!(
18975 actual.len(),
18976 expected.len(),
18977 "case={case} periods: length mismatch"
18978 );
18979 for (pos, (actual, expected)) in actual.iter().zip(expected.iter()).enumerate() {
18980 assert_interval(case, "periods", pos, actual, expected);
18981 }
18982
18983 let step_count = (next(&mut seed) % 20 + 1) as usize;
18984 let step = (next(&mut seed) % 25 + 1) as f64;
18985 let step_end = start + step * step_count as f64;
18986 let actual = interval_range_by_step(start, step_end, step, closed).expect("divides");
18987 let expected = expected_by_step(start, step_end, step, closed);
18988 assert_eq!(
18989 actual.len(),
18990 expected.len(),
18991 "case={case} step: length mismatch"
18992 );
18993 for (pos, (actual, expected)) in actual.iter().zip(expected.iter()).enumerate() {
18994 assert_interval(case, "step", pos, actual, expected);
18995 }
18996 }
18997 }
18998
18999 use super::Timedelta;
19002
19003 #[test]
19004 fn timedelta_add_sums_non_nat() {
19005 let one_hour = Timedelta::NANOS_PER_HOUR;
19006 let one_day = Timedelta::NANOS_PER_DAY;
19007 assert_eq!(Timedelta::add(one_hour, one_day), one_hour + one_day);
19008 }
19009
19010 #[test]
19011 fn timedelta_add_propagates_nat() {
19012 assert_eq!(Timedelta::add(Timedelta::NAT, 100), Timedelta::NAT);
19013 assert_eq!(Timedelta::add(100, Timedelta::NAT), Timedelta::NAT);
19014 assert_eq!(
19015 Timedelta::add(Timedelta::NAT, Timedelta::NAT),
19016 Timedelta::NAT
19017 );
19018 }
19019
19020 #[test]
19021 fn timedelta_add_returns_nat_on_overflow() {
19022 assert_eq!(Timedelta::add(i64::MAX - 10, 100), Timedelta::NAT);
19029 assert_eq!(Timedelta::add(i64::MIN + 10, -100), Timedelta::NAT);
19032 }
19033
19034 #[test]
19035 fn timedelta_sub_subtracts_non_nat() {
19036 let one_hour = Timedelta::NANOS_PER_HOUR;
19037 assert_eq!(
19038 Timedelta::sub(one_hour, Timedelta::NANOS_PER_MIN),
19039 one_hour - Timedelta::NANOS_PER_MIN
19040 );
19041 }
19042
19043 #[test]
19044 fn timedelta_sub_propagates_nat() {
19045 assert_eq!(Timedelta::sub(Timedelta::NAT, 100), Timedelta::NAT);
19046 assert_eq!(Timedelta::sub(100, Timedelta::NAT), Timedelta::NAT);
19047 }
19048
19049 #[test]
19050 fn timedelta_neg_flips_sign_non_nat() {
19051 assert_eq!(Timedelta::neg(5), -5);
19052 assert_eq!(Timedelta::neg(-5), 5);
19053 assert_eq!(Timedelta::neg(0), 0);
19054 }
19055
19056 #[test]
19057 fn timedelta_neg_preserves_nat() {
19058 assert_eq!(Timedelta::neg(Timedelta::NAT), Timedelta::NAT);
19059 }
19060
19061 #[test]
19062 fn timedelta_abs_returns_magnitude() {
19063 assert_eq!(Timedelta::abs(-5), 5);
19064 assert_eq!(Timedelta::abs(5), 5);
19065 assert_eq!(Timedelta::abs(0), 0);
19066 assert_eq!(Timedelta::abs(Timedelta::NAT), Timedelta::NAT);
19067 }
19068
19069 #[test]
19070 fn neg_and_abs_at_the_representable_floor_are_not_overflow_fyr1z() {
19071 const MAX: i64 = i64::MAX;
19089 const MIN_OK: i64 = i64::MIN + 1; assert_eq!(MIN_OK, -MAX);
19094 assert_eq!(Timedelta::NAT, i64::MIN);
19095
19096 assert_eq!(Timedelta::neg(MIN_OK), MAX);
19098 assert_eq!(Timedelta::neg(MAX), MIN_OK);
19099 assert_eq!(Timedelta::abs(MIN_OK), MAX);
19100 assert_eq!(Timedelta::abs(MAX), MAX);
19101
19102 assert_eq!(Timedelta::neg(Timedelta::neg(MIN_OK)), MIN_OK);
19106 assert_ne!(Timedelta::neg(MIN_OK), Timedelta::NAT);
19107 assert_ne!(Timedelta::abs(MIN_OK), Timedelta::NAT);
19108
19109 assert_eq!(Timedelta::neg(Timedelta::NAT), Timedelta::NAT);
19112 assert_eq!(Timedelta::abs(Timedelta::NAT), Timedelta::NAT);
19113 }
19114
19115 #[test]
19116 fn overflow_divergence_surface_is_only_where_pandas_refuses_fyr1z() {
19117 const MAX: i64 = i64::MAX;
19129 const MIN_OK: i64 = i64::MIN + 1;
19130
19131 assert_eq!(Timedelta::div_scalar(MAX, 0), Timedelta::NAT);
19136 assert_eq!(Timedelta::div_scalar(MIN_OK, 0), Timedelta::NAT);
19137 assert_eq!(Timedelta::div_scalar(0, 0), Timedelta::NAT);
19138
19139 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());
19149 assert!(Timestamp::from_nanos(MIN_OK).sub_timedelta(2).is_nat());
19150
19151 assert_eq!(Timedelta::add(MAX, 1), Timedelta::NAT);
19155 assert_eq!(Timedelta::mul_scalar(MAX, 2), Timedelta::NAT);
19156 assert!(Timestamp::from_nanos(MAX).add_timedelta(1).is_nat());
19157
19158 assert_eq!(Timedelta::div_scalar(MAX, 1), MAX);
19160 assert_eq!(Timedelta::div_scalar(-100, 3), -34); assert_eq!(Timedelta::div_scalar(100, -3), -34);
19162 assert_eq!(Timedelta::sub(MIN_OK + 2, 1), MIN_OK + 1);
19163 }
19164
19165 #[test]
19166 fn timedelta_mul_scalar_scales() {
19167 let three_hours = Timedelta::NANOS_PER_HOUR * 3;
19168 assert_eq!(
19169 Timedelta::mul_scalar(Timedelta::NANOS_PER_HOUR, 3),
19170 three_hours
19171 );
19172 assert_eq!(Timedelta::mul_scalar(100, 0), 0);
19173 assert_eq!(Timedelta::mul_scalar(100, -2), -200);
19174 }
19175
19176 #[test]
19177 fn timedelta_mul_scalar_returns_nat_on_overflow() {
19178 assert_eq!(Timedelta::mul_scalar(i64::MAX, 2), Timedelta::NAT);
19181 assert_eq!(Timedelta::mul_scalar(i64::MIN + 1, 2), Timedelta::NAT);
19182 }
19183
19184 #[test]
19185 fn from_unit_nan_is_nat_and_overflow_is_err_8v92m() {
19186 use super::TimedeltaError;
19187
19188 assert_eq!(Timedelta::from_unit(f64::NAN, "s"), Ok(Timedelta::NAT));
19206 assert_ne!(Timedelta::from_unit(f64::NAN, "s"), Ok(0));
19207 assert_eq!(Timedelta::from_unit(f64::NAN, "D"), Ok(Timedelta::NAT));
19208
19209 assert_eq!(
19211 Timedelta::from_unit(f64::INFINITY, "s"),
19212 Err(TimedeltaError::Overflow)
19213 );
19214 assert_eq!(
19215 Timedelta::from_unit(f64::NEG_INFINITY, "s"),
19216 Err(TimedeltaError::Overflow)
19217 );
19218 assert_eq!(
19219 Timedelta::from_unit(1e30, "s"),
19220 Err(TimedeltaError::Overflow)
19221 );
19222 assert_eq!(
19223 Timedelta::from_unit(1e30, "D"),
19224 Err(TimedeltaError::Overflow)
19225 );
19226
19227 assert_eq!(Timedelta::from_unit(1.5, "s"), Ok(1_500_000_000));
19230 assert_eq!(Timedelta::from_unit(0.0, "s"), Ok(0));
19231 assert_eq!(Timedelta::from_unit(-2.5, "s"), Ok(-2_500_000_000));
19232 assert_eq!(Timedelta::from_unit(1.0, "D"), Ok(Timedelta::NANOS_PER_DAY));
19233 assert_eq!(
19234 Timedelta::from_unit(3.0, "h"),
19235 Ok(3 * Timedelta::NANOS_PER_HOUR)
19236 );
19237 let big_days = 100_000.0_f64;
19240 let expected = (big_days * Timedelta::NANOS_PER_DAY as f64).round() as i64;
19241 assert_eq!(Timedelta::from_unit(big_days, "D"), Ok(expected));
19242 assert!(expected > 0, "fixture must stay in range to be a control");
19243
19244 assert!(matches!(
19247 Timedelta::from_unit(1.0, "nonsense-unit"),
19248 Err(TimedeltaError::InvalidFormat(_))
19249 ));
19250 assert!(matches!(
19251 Timedelta::from_unit(f64::NAN, "nonsense-unit"),
19252 Err(TimedeltaError::InvalidFormat(_)),
19253 ));
19254
19255 let huge = format!("{} days", "9".repeat(18));
19260 assert!(matches!(
19261 Timedelta::parse(&huge),
19262 Err(TimedeltaError::Overflow)
19263 ));
19264 assert!(matches!(
19265 Timedelta::parse("1e100 days"),
19266 Err(TimedeltaError::InvalidFormat(_))
19267 ));
19268 }
19269
19270 #[test]
19271 fn rounding_and_ms_us_overflow_never_fabricates_a_finite_value_kyd16() {
19272 const MAX: i64 = i64::MAX;
19291 const MIN_OK: i64 = i64::MIN + 1;
19292 const DAY: i64 = Timedelta::NANOS_PER_DAY;
19293
19294 let rounded = Timedelta::round(MAX, "D");
19296 assert_eq!(
19297 rounded,
19298 Timedelta::NAT,
19299 "rounding i64::MAX up to a whole day overflows; the old unchecked \
19300 multiply panicked in debug and wrapped in release"
19301 );
19302 assert!(
19306 rounded == Timedelta::NAT || rounded > 0,
19307 "a positive duration must never round to a negative one"
19308 );
19309 assert_eq!(Timedelta::round(MIN_OK, "D"), Timedelta::NAT);
19310
19311 assert_eq!(Timedelta::ceil(MAX, "D"), Timedelta::NAT);
19313 assert_eq!(Timedelta::floor(MIN_OK, "D"), Timedelta::NAT);
19314 assert!(Timestamp::from_nanos(MAX).ceil_to(DAY).is_nat());
19315 assert!(Timestamp::from_nanos(MAX).round_to(DAY).is_nat());
19316 assert!(Timestamp::from_nanos(MIN_OK).floor_to(DAY).is_nat());
19317 assert!(Timestamp::from_nanos(MIN_OK).round_to(DAY).is_nat());
19318
19319 assert!(Timestamp::from_millis(MAX, None).is_nat());
19321 assert!(Timestamp::from_millis(MIN_OK, None).is_nat());
19322 assert!(Timestamp::from_micros(MAX, None).is_nat());
19323 assert!(Timestamp::from_micros(MIN_OK, Some("US/Eastern")).is_nat());
19324
19325 let max_floor = Timestamp::from_nanos(MAX).floor_to(DAY);
19332 assert!(!max_floor.is_nat(), "Timestamp.max.floor(D) must succeed");
19333 assert_eq!(max_floor.nanos, (MAX / DAY) * DAY);
19334 assert_eq!(Timedelta::floor(MAX, "D"), (MAX / DAY) * DAY);
19335 assert_eq!(
19336 Timedelta::ceil(MIN_OK, "D"),
19337 (MIN_OK.div_euclid(DAY) + 1) * DAY
19338 );
19339
19340 let hour = Timedelta::NANOS_PER_HOUR;
19342 assert_eq!(Timedelta::floor(90 * 60 * 1_000_000_000, "h"), hour);
19343 assert_eq!(Timedelta::ceil(90 * 60 * 1_000_000_000, "h"), 2 * hour);
19344 assert_eq!(Timedelta::round(90 * 60 * 1_000_000_000, "h"), 2 * hour);
19345 assert_eq!(Timedelta::round(-90 * 60 * 1_000_000_000, "h"), -2 * hour);
19346 assert_eq!(Timedelta::round(29 * 60 * 1_000_000_000, "h"), 0);
19347 assert_eq!(Timestamp::from_millis(1_500, None).nanos, 1_500_000_000);
19348 assert_eq!(Timestamp::from_micros(-2_000, None).nanos, -2_000_000);
19349 assert_eq!(
19350 Timestamp::from_nanos(hour + 1).floor_to(hour).nanos,
19351 hour,
19352 "in-range floor unchanged"
19353 );
19354 assert_eq!(
19355 Timestamp::from_nanos(hour + 1).ceil_to(hour).nanos,
19356 2 * hour,
19357 "in-range ceil unchanged"
19358 );
19359
19360 assert_eq!(Timedelta::round(Timedelta::NAT, "D"), Timedelta::NAT);
19362 assert_eq!(Timedelta::floor(Timedelta::NAT, "D"), Timedelta::NAT);
19363 assert_eq!(Timedelta::ceil(1_000, "nonsense-unit"), Timedelta::NAT);
19364 assert!(Timestamp::nat().ceil_to(DAY).is_nat());
19365 assert!(Timestamp::from_nanos(0).round_to(0).is_nat());
19366 assert_eq!(
19368 Timestamp::from_nanos_tz(hour + 1, "US/Eastern")
19369 .ceil_to(hour)
19370 .tz
19371 .as_deref(),
19372 Some("US/Eastern")
19373 );
19374 }
19375
19376 #[test]
19377 fn timedelta_mul_scalar_propagates_nat() {
19378 assert_eq!(Timedelta::mul_scalar(Timedelta::NAT, 5), Timedelta::NAT);
19379 }
19380
19381 #[test]
19382 fn arithmetic_overflow_never_fabricates_a_finite_value_lgyy8() {
19383 const MAX: i64 = i64::MAX;
19398 const MIN_OK: i64 = i64::MIN + 1; assert_eq!(Timedelta::add(MAX, 1), Timedelta::NAT);
19402 assert_eq!(Timedelta::add(MAX - 10, 100), Timedelta::NAT);
19403 assert_eq!(Timedelta::sub(MAX, -1), Timedelta::NAT);
19404 assert_eq!(Timedelta::mul_scalar(MAX, 2), Timedelta::NAT);
19405 assert_eq!(Timedelta::mul_scalar(MAX / 2 + 2, 2), Timedelta::NAT);
19406 assert!(Timestamp::from_nanos(MAX).add_timedelta(1).is_nat());
19407 assert!(Timestamp::from_nanos(MAX).sub_timedelta(-1).is_nat());
19408 assert_eq!(
19412 Timestamp::from_nanos(MAX).sub_timestamp(&Timestamp::from_nanos(MIN_OK)),
19413 Timedelta::NAT
19414 );
19415
19416 assert_eq!(Timedelta::add(MIN_OK, -1), Timedelta::NAT);
19418 assert_eq!(Timedelta::add(MIN_OK, -2), Timedelta::NAT);
19419 assert_eq!(Timedelta::sub(MIN_OK, 1), Timedelta::NAT);
19420 assert_eq!(Timedelta::mul_scalar(MIN_OK, 2), Timedelta::NAT);
19421 assert!(Timestamp::from_nanos(MIN_OK).sub_timedelta(1).is_nat());
19422 assert!(Timestamp::from_nanos(MIN_OK).add_timedelta(-1).is_nat());
19423 assert_eq!(
19424 Timestamp::from_nanos(MIN_OK).sub_timestamp(&Timestamp::from_nanos(MAX)),
19425 Timedelta::NAT
19426 );
19427
19428 assert_eq!(Timedelta::add(MAX - 1, 1), MAX);
19434 assert_eq!(Timedelta::add(MAX, 0), MAX);
19435 assert_eq!(Timedelta::sub(MAX, 1), MAX - 1);
19436 assert_eq!(Timedelta::add(MIN_OK + 1, -1), MIN_OK);
19437 assert_eq!(Timedelta::mul_scalar(MAX / 2, 2), (MAX / 2) * 2);
19438 assert_eq!(Timedelta::mul_scalar(MIN_OK, 1), MIN_OK);
19439 assert_eq!(Timestamp::from_nanos(MAX - 1).add_timedelta(1).nanos, MAX);
19440 assert_eq!(
19441 Timestamp::from_nanos(MIN_OK + 1).sub_timedelta(1).nanos,
19442 MIN_OK
19443 );
19444 assert_eq!(
19445 Timestamp::from_nanos(MAX).sub_timestamp(&Timestamp::from_nanos(0)),
19446 MAX
19447 );
19448 assert_eq!(Timedelta::add(1_000, 2_345), 3_345);
19450 assert_eq!(Timedelta::sub(1_000, 2_345), -1_345);
19451 assert_eq!(Timedelta::mul_scalar(-7, 6), -42);
19452
19453 assert_eq!(MIN_OK - 1, i64::MIN);
19460 assert_eq!(Timedelta::sub(MIN_OK, 1), Timedelta::NAT);
19461 assert_eq!(Timedelta::add(MIN_OK, 0), MIN_OK);
19462
19463 assert!(Timestamp::nat().add_timedelta(1).is_nat());
19466 assert!(
19467 Timestamp::from_nanos(0)
19468 .add_timedelta(Timedelta::NAT)
19469 .is_nat()
19470 );
19471 let tzed = Timestamp::from_nanos_tz(MAX, "US/Eastern");
19472 let overflowed = tzed.add_timedelta(1);
19473 assert!(overflowed.is_nat());
19474 assert_eq!(overflowed.tz, None, "an overflow NaT carries no zone");
19475 assert_eq!(
19477 Timestamp::from_nanos_tz(0, "US/Eastern")
19478 .add_timedelta(Timedelta::NANOS_PER_DAY)
19479 .tz
19480 .as_deref(),
19481 Some("US/Eastern")
19482 );
19483 }
19484
19485 #[test]
19486 fn timedelta_div_scalar_floor_divides() {
19487 assert_eq!(Timedelta::div_scalar(100, 3), 33);
19489 assert_eq!(Timedelta::div_scalar(-100, 3), -34);
19490 assert_eq!(Timedelta::div_scalar(100, -3), -34);
19491 assert_eq!(Timedelta::div_scalar(-100, -3), 33);
19492 }
19493
19494 #[test]
19495 fn timedelta_div_scalar_zero_divisor_returns_nat() {
19496 assert_eq!(Timedelta::div_scalar(100, 0), Timedelta::NAT);
19497 }
19498
19499 #[test]
19500 fn timedelta_div_scalar_min_neg_one_propagates_nat() {
19501 assert_eq!(Timedelta::div_scalar(i64::MIN, -1), Timedelta::NAT);
19504 assert_eq!(Timedelta::div_scalar(i64::MIN + 1, -1), i64::MAX);
19506 }
19507
19508 #[test]
19509 fn timedelta_div_scalar_propagates_nat() {
19510 assert_eq!(Timedelta::div_scalar(Timedelta::NAT, 10), Timedelta::NAT);
19511 }
19512
19513 #[test]
19514 fn timedelta_div_timedelta_returns_float_ratio() {
19515 let two_hours = Timedelta::NANOS_PER_HOUR * 2;
19516 let one_hour = Timedelta::NANOS_PER_HOUR;
19517 assert!((Timedelta::div_timedelta(two_hours, one_hour) - 2.0).abs() < 1e-12);
19518 assert!((Timedelta::div_timedelta(one_hour, two_hours) - 0.5).abs() < 1e-12);
19519 }
19520
19521 #[test]
19522 fn timedelta_div_timedelta_nat_returns_nan() {
19523 assert!(Timedelta::div_timedelta(Timedelta::NAT, 100).is_nan());
19524 assert!(Timedelta::div_timedelta(100, Timedelta::NAT).is_nan());
19525 }
19526
19527 use super::Timestamp;
19530
19531 #[test]
19532 fn timestamp_from_nanos_is_naive_utc() {
19533 let ts = Timestamp::from_nanos(1_700_000_000_000_000_000);
19534 assert_eq!(ts.nanos, 1_700_000_000_000_000_000);
19535 assert_eq!(ts.tz, None);
19536 assert!(!ts.is_nat());
19537 }
19538
19539 #[test]
19540 fn timestamp_from_nanos_tz_carries_tz_name() {
19541 let ts = Timestamp::from_nanos_tz(1_700_000_000_000_000_000, "US/Eastern");
19542 assert_eq!(ts.tz.as_deref(), Some("US/Eastern"));
19543 }
19544
19545 #[test]
19546 fn timestamp_now_returns_current_time() {
19547 let before = std::time::SystemTime::now()
19548 .duration_since(std::time::UNIX_EPOCH)
19549 .unwrap()
19550 .as_nanos() as i64;
19551 let ts = Timestamp::now();
19552 let after = std::time::SystemTime::now()
19553 .duration_since(std::time::UNIX_EPOCH)
19554 .unwrap()
19555 .as_nanos() as i64;
19556 assert!(ts.nanos >= before);
19557 assert!(ts.nanos <= after);
19558 assert!(!ts.is_nat());
19559 }
19560
19561 #[test]
19562 fn timestamp_today_returns_midnight() {
19563 let ts = Timestamp::today();
19564 assert!(!ts.is_nat());
19565 assert_eq!(ts.hour(), Some(0));
19567 assert_eq!(ts.minute(), Some(0));
19568 assert_eq!(ts.second(), Some(0));
19569 }
19570
19571 #[test]
19572 fn timestamp_add_timedelta_shifts_nanos_and_preserves_tz() {
19573 let ts = Timestamp::from_nanos_tz(0, "US/Eastern");
19574 let one_day = Timedelta::NANOS_PER_DAY;
19575 let shifted = ts.add_timedelta(one_day);
19576 assert_eq!(shifted.nanos, one_day);
19577 assert_eq!(shifted.tz.as_deref(), Some("US/Eastern"));
19578 }
19579
19580 #[test]
19581 fn timestamp_add_timedelta_returns_nat_on_overflow() {
19582 let ts = Timestamp::from_nanos(i64::MAX - 10);
19586 assert!(ts.add_timedelta(100).is_nat());
19587 }
19588
19589 #[test]
19590 fn timestamp_add_timedelta_propagates_nat() {
19591 assert!(Timestamp::nat().add_timedelta(100).is_nat());
19593 assert!(
19595 Timestamp::from_nanos(0)
19596 .add_timedelta(Timedelta::NAT)
19597 .is_nat()
19598 );
19599 }
19600
19601 #[test]
19602 fn timestamp_sub_timedelta_shifts_backward() {
19603 let ts = Timestamp::from_nanos(1_000);
19604 let shifted = ts.sub_timedelta(Timedelta::NANOS_PER_MICRO);
19605 assert_eq!(shifted.nanos, 0);
19606 }
19607
19608 #[test]
19609 fn timestamp_sub_timestamp_returns_timedelta_nanos() {
19610 let t0 = Timestamp::from_nanos(0);
19611 let t1 = Timestamp::from_nanos(Timedelta::NANOS_PER_HOUR);
19612 assert_eq!(t1.sub_timestamp(&t0), Timedelta::NANOS_PER_HOUR);
19613 assert_eq!(t0.sub_timestamp(&t1), -Timedelta::NANOS_PER_HOUR);
19614 }
19615
19616 #[test]
19617 fn timestamp_sub_timestamp_nat_propagates() {
19618 let ts = Timestamp::from_nanos(1_000);
19619 assert_eq!(Timestamp::nat().sub_timestamp(&ts), Timedelta::NAT);
19620 assert_eq!(ts.sub_timestamp(&Timestamp::nat()), Timedelta::NAT);
19621 }
19622
19623 #[test]
19624 fn timestamp_semantic_eq_treats_two_nat_as_equal() {
19625 assert!(Timestamp::nat().semantic_eq(&Timestamp::nat()));
19626 assert!(!Timestamp::nat().semantic_eq(&Timestamp::from_nanos(0)));
19627 assert!(!Timestamp::from_nanos(0).semantic_eq(&Timestamp::nat()));
19628 }
19629
19630 #[test]
19631 fn timestamp_partial_cmp_orders_by_nanos_nat_is_incomparable() {
19632 use std::cmp::Ordering;
19633 let a = Timestamp::from_nanos(0);
19634 let b = Timestamp::from_nanos(100);
19635 assert_eq!(a.partial_cmp(&b), Some(Ordering::Less));
19636 assert_eq!(b.partial_cmp(&a), Some(Ordering::Greater));
19637 assert_eq!(a.partial_cmp(&a), Some(Ordering::Equal));
19638 assert_eq!(a.partial_cmp(&Timestamp::nat()), None);
19639 assert_eq!(Timestamp::nat().partial_cmp(&Timestamp::nat()), None);
19640 }
19641
19642 #[test]
19643 fn time_zone_offsets_and_wall_clock_conversions_follow_pandas() {
19644 use crate::{
19645 TimeZoneError, tz_abbreviation, tz_canonical_name, tz_offset_seconds,
19646 tz_utc_to_wall_nanos, tz_validate, tz_wall_to_utc_nanos,
19647 };
19648 let hour = 3_600_000_000_000_i64;
19649 let instant = 1_710_081_000_000_000_000_i64;
19652 assert_eq!(tz_offset_seconds("Asia/Tokyo", instant), Ok(9 * 3_600));
19653 assert_eq!(tz_offset_seconds("US/Eastern", instant), Ok(-4 * 3_600));
19654 assert_eq!(
19655 tz_offset_seconds("US/Eastern", instant - 24 * hour),
19656 Ok(-5 * 3_600)
19657 );
19658 assert_eq!(tz_offset_seconds("+05:30", 0), Ok(19_800));
19659 assert_eq!(tz_offset_seconds("UTC+05:30", 0), Ok(19_800));
19660 assert_eq!(tz_offset_seconds("-03:00", 0), Ok(-10_800));
19661 assert_eq!(tz_offset_seconds("UTC", instant), Ok(0));
19662 assert_eq!(
19663 tz_utc_to_wall_nanos("Asia/Tokyo", instant),
19664 Ok(instant + 9 * hour)
19665 );
19666 let wall_noon = 19_723 * 24 * hour + 12 * hour;
19668 assert_eq!(
19669 tz_wall_to_utc_nanos("US/Eastern", wall_noon),
19670 Ok(wall_noon + 5 * hour)
19671 );
19672 assert_eq!(
19673 tz_utc_to_wall_nanos("US/Eastern", wall_noon + 5 * hour),
19674 Ok(wall_noon)
19675 );
19676 assert_eq!(tz_wall_to_utc_nanos("US/Eastern", i64::MIN), Ok(i64::MIN));
19678 assert_eq!(tz_utc_to_wall_nanos("US/Eastern", i64::MIN), Ok(i64::MIN));
19679 let skipped = 19_792 * 24 * hour + 2 * hour + 30 * 60_000_000_000;
19683 assert_eq!(
19684 tz_wall_to_utc_nanos("US/Eastern", skipped),
19685 Err(TimeZoneError::NonExistent("2024-03-10 02:30:00".to_owned()))
19686 );
19687 let repeated = 20_030 * 24 * hour + hour + 30 * 60_000_000_000;
19688 assert_eq!(
19689 tz_wall_to_utc_nanos("US/Eastern", repeated),
19690 Err(TimeZoneError::Ambiguous("2024-11-03 01:30:00".to_owned()))
19691 );
19692 assert_eq!(
19693 tz_offset_seconds("Mars/Olympus", 0),
19694 Err(TimeZoneError::Unknown("Mars/Olympus".to_owned()))
19695 );
19696 assert!(tz_validate("+24:00").is_err());
19697 assert!(tz_validate("+5:30").is_err());
19698 assert!(tz_validate("Europe/Paris").is_ok());
19699 assert_eq!(tz_canonical_name("+05:30").as_deref(), Ok("UTC+05:30"));
19701 assert_eq!(tz_canonical_name("UTC-03:00").as_deref(), Ok("UTC-03:00"));
19702 assert_eq!(tz_canonical_name("+00:00").as_deref(), Ok("UTC"));
19703 assert_eq!(tz_canonical_name("Z").as_deref(), Ok("UTC"));
19704 assert_eq!(tz_canonical_name("US/Eastern").as_deref(), Ok("US/Eastern"));
19705 assert_eq!(tz_abbreviation("US/Eastern", instant).as_deref(), Ok("EDT"));
19707 assert_eq!(
19708 tz_abbreviation("US/Eastern", instant - 24 * hour).as_deref(),
19709 Ok("EST")
19710 );
19711 assert_eq!(tz_abbreviation("+05:30", 0).as_deref(), Ok("UTC+05:30"));
19712 }
19713
19714 #[test]
19721 fn tz_localize_policies_follow_pandas_84w06() {
19722 use super::{
19723 AmbiguousTime as A, NonexistentTime as N, TimeZoneError,
19724 tz_wall_to_utc_nanos_with as at,
19725 };
19726 let hour = 3_600_000_000_000_i64;
19727 let minute = 60_000_000_000_i64;
19728 let skipped = 19_792 * 24 * hour + 2 * hour + 30 * minute;
19729 let transition = 19_792 * 24 * hour + 7 * hour;
19730 let zone = "America/New_York";
19731 assert_eq!(at(zone, skipped, A::Raise, N::ShiftForward), Ok(transition));
19732 assert_eq!(
19733 at(zone, skipped, A::Raise, N::ShiftBackward),
19734 Ok(transition - 1)
19735 );
19736 assert_eq!(at(zone, skipped, A::Raise, N::NaT), Ok(i64::MIN));
19737 assert_eq!(
19738 at(zone, skipped, A::Raise, N::Shift(hour)),
19739 Ok(transition + 30 * minute)
19740 );
19741 let repeated = 20_030 * 24 * hour + hour + 30 * minute;
19742 assert_eq!(
19743 at(zone, repeated, A::Earliest, N::Raise),
19744 Ok(repeated + 4 * hour)
19745 );
19746 assert_eq!(
19747 at(zone, repeated, A::Latest, N::Raise),
19748 Ok(repeated + 5 * hour)
19749 );
19750 assert_eq!(at(zone, repeated, A::NaT, N::Raise), Ok(i64::MIN));
19751 let noon = 19_723 * 24 * hour + 12 * hour;
19754 assert_eq!(at(zone, noon, A::NaT, N::NaT), Ok(noon + 5 * hour));
19755 assert_eq!(
19756 at(zone, skipped, A::NaT, N::Raise),
19757 Err(TimeZoneError::NonExistent("2024-03-10 02:30:00".to_owned()))
19758 );
19759 assert_eq!(
19760 at(zone, repeated, A::Raise, N::NaT),
19761 Err(TimeZoneError::Ambiguous("2024-11-03 01:30:00".to_owned()))
19762 );
19763 }
19764
19765 #[test]
19773 fn batch_tz_conversions_match_each_value_6pqf3() {
19774 use super::{
19775 AmbiguousTime as A, NonexistentTime as N, TimeZoneError, tz_utc_to_wall_nanos,
19776 tz_utc_to_wall_nanos_all, tz_wall_to_utc_nanos_all, tz_wall_to_utc_nanos_with,
19777 };
19778 const HOUR: i64 = 3_600_000_000_000;
19779 const MINUTE: i64 = 60_000_000_000;
19780 const DAY: i64 = 24 * HOUR;
19781 let (year_start, year_end) = (19_723 * DAY, 20_089 * DAY);
19782 let mut values: Vec<i64> = (year_start..year_end)
19783 .step_by(usize::try_from(37 * MINUTE).unwrap())
19784 .collect();
19785 for hour in (year_start..year_end).step_by(usize::try_from(HOUR).unwrap()) {
19786 values.extend([hour - 1, hour, hour + 1]);
19787 }
19788 for change_day in [19_792, 20_030, 19_813, 20_023, 19_820, 20_002] {
19789 values.extend((0..2 * 24 * 60).map(|minute| (change_day - 1) * DAY + minute * MINUTE));
19790 }
19791 let mut state = 0x2545_f491_4f6c_dd1d_u64;
19792 for _ in 0..3_000 {
19793 state = state
19794 .wrapping_mul(6_364_136_223_846_793_005)
19795 .wrapping_add(1_442_695_040_888_963_407);
19796 values.push(i64::try_from(state >> 2).unwrap() - 2_000_000_000_000_000_000);
19797 }
19798 values.extend([i64::MIN, 19_792 * DAY, i64::MIN]);
19799 let policies = [
19800 (A::NaT, N::NaT),
19801 (A::Earliest, N::ShiftForward),
19802 (A::Latest, N::ShiftBackward),
19803 (A::NaT, N::Shift(30 * MINUTE)),
19804 ];
19805 for zone in [
19806 "US/Eastern",
19807 "Europe/London",
19808 "Australia/Lord_Howe",
19809 "+05:30",
19810 "UTC",
19811 ] {
19812 let one_by_one: Result<Vec<i64>, TimeZoneError> = values
19813 .iter()
19814 .map(|&nanos| tz_utc_to_wall_nanos(zone, nanos))
19815 .collect();
19816 assert_eq!(
19817 tz_utc_to_wall_nanos_all(zone, &values),
19818 one_by_one,
19819 "{zone}"
19820 );
19821 for (ambiguous, nonexistent) in policies {
19822 let one_by_one: Result<Vec<i64>, TimeZoneError> = values
19823 .iter()
19824 .map(|&wall| tz_wall_to_utc_nanos_with(zone, wall, ambiguous, nonexistent))
19825 .collect();
19826 assert_eq!(
19827 tz_wall_to_utc_nanos_all(zone, &values, ambiguous, nonexistent),
19828 one_by_one,
19829 "{zone} {ambiguous:?} {nonexistent:?}"
19830 );
19831 }
19832 let one_by_one: Result<Vec<i64>, TimeZoneError> = values
19833 .iter()
19834 .map(|&wall| tz_wall_to_utc_nanos_with(zone, wall, A::Raise, N::Raise))
19835 .collect();
19836 assert_eq!(
19837 tz_wall_to_utc_nanos_all(zone, &values, A::Raise, N::Raise),
19838 one_by_one,
19839 "{zone} raise"
19840 );
19841 }
19842 let skipped = 19_792 * DAY + 2 * HOUR + 30 * MINUTE;
19843 let run: Vec<i64> = (0..8)
19845 .map(|step| 19_792 * DAY + HOUR + 10 * MINUTE + step * 20 * MINUTE)
19846 .collect();
19847 assert_eq!(
19848 tz_wall_to_utc_nanos_all("US/Eastern", &run, A::Raise, N::Raise),
19849 Err(TimeZoneError::NonExistent("2024-03-10 02:10:00".to_owned()))
19850 );
19851 let placed = tz_wall_to_utc_nanos_all("US/Eastern", &run, A::Raise, N::NaT).unwrap();
19852 let expected: Vec<i64> = run
19853 .iter()
19854 .enumerate()
19855 .map(|(step, &wall)| match step {
19856 0..3 => wall + 5 * HOUR,
19857 3..6 => i64::MIN,
19858 _ => wall + 4 * HOUR,
19859 })
19860 .collect();
19861 assert_eq!(placed, expected);
19862 let howe = 20_002 * DAY + 2 * HOUR + 10 * MINUTE;
19866 assert_eq!(
19867 tz_wall_to_utc_nanos_all("Australia/Lord_Howe", &[howe], A::Raise, N::ShiftForward),
19868 Ok(vec![20_002 * DAY - 8 * HOUR])
19869 );
19870 assert_eq!(
19871 tz_wall_to_utc_nanos_all("Australia/Lord_Howe", &[howe], A::Raise, N::ShiftBackward),
19872 Ok(vec![20_002 * DAY - 8 * HOUR - 30 * MINUTE - 1])
19873 );
19874 for (wall, text) in [
19875 (skipped + 500_000_000, "2024-03-10 02:30:00.500000"),
19876 (skipped + 1, "2024-03-10 02:30:00.000000001"),
19877 ] {
19878 assert_eq!(
19879 tz_wall_to_utc_nanos_all("US/Eastern", &[wall], A::Raise, N::Raise),
19880 Err(TimeZoneError::NonExistent(text.to_owned()))
19881 );
19882 }
19883 }
19884
19885 #[test]
19886 fn timestamp_display_matches_phase2_debug_format() {
19887 assert_eq!(Timestamp::from_nanos(42).to_string(), "Timestamp[42, UTC]");
19888 assert_eq!(
19889 Timestamp::from_nanos_tz(42, "US/Eastern").to_string(),
19890 "Timestamp[42, US/Eastern]"
19891 );
19892 assert_eq!(Timestamp::nat().to_string(), "NaT");
19893 }
19894
19895 #[test]
19896 fn a_naive_timestamp_cell_casts_to_its_str_srzqw() {
19897 let text = |nanos: i64| cast_scalar(&Scalar::Datetime64(nanos), DType::Utf8);
19901 let midnight = 1_711_929_600_000_000_000;
19902 assert_eq!(
19903 text(midnight),
19904 Ok(Scalar::Utf8("2024-04-01 00:00:00".into()))
19905 );
19906 assert_eq!(
19907 text(midnight + 1_000),
19908 Ok(Scalar::Utf8("2024-04-01 00:00:00.000001".into()))
19909 );
19910 assert_eq!(
19911 text(midnight + 1),
19912 Ok(Scalar::Utf8("2024-04-01 00:00:00.000000001".into()))
19913 );
19914 assert_eq!(
19915 text(-1),
19916 Ok(Scalar::Utf8("1969-12-31 23:59:59.999999999".into()))
19917 );
19918 assert_eq!(text(Timestamp::NAT), Ok(Scalar::Utf8("NaT".into())));
19919 assert_eq!(
19921 crate::timestamp_text_in_zone(midnight, "US/Eastern"),
19922 "2024-03-31 20:00:00-04:00"
19923 );
19924 }
19925
19926 #[test]
19927 fn timestamp_value_and_unit_match_pandas_l0edr() {
19928 let ts = Timestamp::from_nanos(1_000_000_123);
19929 assert_eq!(ts.value(), 1_000_000_123);
19930 assert_eq!(ts.unit(), Some("ns"));
19931
19932 let nat = Timestamp::nat();
19933 assert_eq!(nat.value(), Timestamp::NAT);
19934 assert_eq!(nat.unit(), None);
19935 }
19936
19937 #[test]
19938 fn timestamp_numpy_datetime64_materializers_match_value_twksi() {
19939 let ts = Timestamp::from_nanos(1_000_000_123);
19940 assert_eq!(ts.asm8(), ts.value());
19941 assert_eq!(ts.to_datetime64(), ts.value());
19942 assert_eq!(ts.to_numpy(), ts.value());
19943
19944 let nat = Timestamp::nat();
19945 assert_eq!(nat.asm8(), Timestamp::NAT);
19946 assert_eq!(nat.to_datetime64(), Timestamp::NAT);
19947 assert_eq!(nat.to_numpy(), Timestamp::NAT);
19948 }
19949
19950 #[test]
19951 fn timestamp_timestamp_accessor_matches_pandas_microsecond_rounding_py0h3() {
19952 assert_eq!(Timestamp::from_nanos(0).timestamp(), Ok(0.0));
19953 assert_eq!(Timestamp::from_nanos(1_500_000_000).timestamp(), Ok(1.5));
19954 assert_eq!(Timestamp::from_nanos(500).timestamp(), Ok(0.0));
19955 assert_eq!(Timestamp::from_nanos(501).timestamp(), Ok(0.000001));
19956 assert_eq!(Timestamp::from_nanos(2_500).timestamp(), Ok(0.000003));
19957
19958 assert!(matches!(
19959 Timestamp::from_nanos(-500).timestamp(),
19960 Ok(value) if value == -0.0 && value.is_sign_negative()
19961 ));
19962 assert_eq!(Timestamp::from_nanos(-2_500).timestamp(), Ok(-0.000003));
19963 assert_eq!(
19964 Timestamp::nat().timestamp(),
19965 Err(TypeError::ValueIsMissing {
19966 kind: NullKind::NaT,
19967 })
19968 );
19969 }
19970
19971 #[test]
19972 fn timestamp_roundtrips_through_serde_json() {
19973 let naive = Timestamp::from_nanos(1_700_000_000_000_000_000);
19974 let json = serde_json::to_string(&naive).expect("serialize");
19975 let back: Timestamp = serde_json::from_str(&json).expect("deserialize");
19976 assert_eq!(naive, back);
19977
19978 let tz_aware = Timestamp::from_nanos_tz(1_700_000_000_000_000_000, "US/Eastern");
19979 let json = serde_json::to_string(&tz_aware).expect("serialize");
19980 let back: Timestamp = serde_json::from_str(&json).expect("deserialize");
19981 assert_eq!(tz_aware, back);
19982 }
19983
19984 #[test]
19985 fn timestamp_is_send_and_sync() {
19986 fn assert_send_sync<T: Send + Sync>() {}
19987 assert_send_sync::<Timestamp>();
19988 }
19989
19990 #[test]
19993 fn timestamp_pre_epoch_accessors_floor_not_truncate() {
19994 let ts = Timestamp::from_nanos(-1);
19998 assert_eq!(ts.year(), Some(1969));
19999 assert_eq!(ts.month(), Some(12));
20000 assert_eq!(ts.day(), Some(31));
20001 assert_eq!(ts.hour(), Some(23));
20002 assert_eq!(ts.minute(), Some(59));
20003 assert_eq!(ts.second(), Some(59));
20004 assert_eq!(ts.microsecond(), Some(999_999));
20005 assert_eq!(ts.nanosecond(), Some(999));
20006 assert_eq!(ts.dayofweek(), Some(2));
20008
20009 let noon = Timestamp::from_nanos(-43200 * Timedelta::NANOS_PER_SEC);
20011 assert_eq!(noon.year(), Some(1969));
20012 assert_eq!(noon.month(), Some(12));
20013 assert_eq!(noon.day(), Some(31));
20014 assert_eq!(noon.hour(), Some(12));
20015
20016 let midnight = Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY);
20018 assert_eq!(midnight.year(), Some(1969));
20019 assert_eq!(midnight.day(), Some(31));
20020 assert_eq!(midnight.hour(), Some(0));
20021 }
20022
20023 #[test]
20024 fn timestamp_floor_to_rounds_down() {
20025 let h = Timedelta::NANOS_PER_HOUR;
20027 let twelve_h = h * 12;
20028 let twelve_thirty_four =
20029 twelve_h + Timedelta::NANOS_PER_MIN * 34 + Timedelta::NANOS_PER_SEC * 56;
20030 let ts = Timestamp::from_nanos(twelve_thirty_four);
20031 let floored = ts.floor_to(h);
20032 assert_eq!(floored.nanos, twelve_h);
20033 }
20034
20035 #[test]
20036 fn timestamp_floor_to_handles_already_aligned() {
20037 let h = Timedelta::NANOS_PER_HOUR;
20039 let twelve_h = h * 12;
20040 let ts = Timestamp::from_nanos(twelve_h);
20041 assert_eq!(ts.floor_to(h).nanos, twelve_h);
20042 }
20043
20044 #[test]
20045 fn timestamp_floor_to_handles_negative_nanos() {
20046 let ts = Timestamp::from_nanos(-100);
20050 assert_eq!(ts.floor_to(60).nanos, -120);
20051 }
20052
20053 #[test]
20054 fn timestamp_floor_to_returns_nat_on_axis_underflow_30hdi() {
20055 let ts = Timestamp::from_nanos(i64::MIN + 1);
20056 assert!(ts.floor_to(10).is_nat());
20057
20058 let safe = Timestamp::from_nanos(i64::MIN + 10);
20059 assert_eq!(safe.floor_to(10).nanos, i64::MIN + 8);
20060
20061 let tz = Timestamp::from_nanos_tz(-100, "UTC").floor_to(60);
20062 assert_eq!(tz.nanos, -120);
20063 assert_eq!(tz.tz.as_deref(), Some("UTC"));
20064 }
20065
20066 #[test]
20067 fn timestamp_ceil_to_rounds_up() {
20068 let h = Timedelta::NANOS_PER_HOUR;
20070 let twelve_h = h * 12;
20071 let thirteen_h = h * 13;
20072 let twelve_thirty_four =
20073 twelve_h + Timedelta::NANOS_PER_MIN * 34 + Timedelta::NANOS_PER_SEC * 56;
20074 let ts = Timestamp::from_nanos(twelve_thirty_four);
20075 assert_eq!(ts.ceil_to(h).nanos, thirteen_h);
20076 }
20077
20078 #[test]
20079 fn timestamp_ceil_to_no_op_on_aligned() {
20080 let h = Timedelta::NANOS_PER_HOUR;
20081 let twelve_h = h * 12;
20082 let ts = Timestamp::from_nanos(twelve_h);
20083 assert_eq!(ts.ceil_to(h).nanos, twelve_h);
20084 }
20085
20086 #[test]
20087 fn timestamp_round_to_rounds_to_nearest() {
20088 let h = Timedelta::NANOS_PER_HOUR;
20090 let twelve_h = h * 12;
20091 let twelve_thirty_one_sec =
20092 twelve_h + Timedelta::NANOS_PER_MIN * 30 + Timedelta::NANOS_PER_SEC;
20093 let ts = Timestamp::from_nanos(twelve_thirty_one_sec);
20094 assert_eq!(ts.round_to(h).nanos, h * 13);
20095
20096 let twelve_twenty_nine_sec =
20098 twelve_h + Timedelta::NANOS_PER_MIN * 29 + Timedelta::NANOS_PER_SEC * 59;
20099 let ts = Timestamp::from_nanos(twelve_twenty_nine_sec);
20100 assert_eq!(ts.round_to(h).nanos, twelve_h);
20101 }
20102
20103 #[test]
20104 fn timestamp_round_to_bankers_tie_to_even() {
20105 assert_eq!(Timestamp::from_nanos(5).round_to(10).nanos, 0);
20111 assert_eq!(Timestamp::from_nanos(15).round_to(10).nanos, 20);
20112 assert_eq!(Timestamp::from_nanos(25).round_to(10).nanos, 20);
20113 assert_eq!(Timestamp::from_nanos(35).round_to(10).nanos, 40);
20114 }
20115
20116 #[test]
20117 fn timestamp_round_to_zero_unit_returns_nat() {
20118 let ts = Timestamp::from_nanos(100);
20119 assert!(ts.round_to(0).is_nat());
20120 assert!(ts.floor_to(0).is_nat());
20121 assert!(ts.ceil_to(0).is_nat());
20122 }
20123
20124 #[test]
20125 fn timestamp_round_to_negative_unit_returns_nat() {
20126 let ts = Timestamp::from_nanos(100);
20127 assert!(ts.round_to(-10).is_nat());
20128 assert!(ts.floor_to(-10).is_nat());
20129 assert!(ts.ceil_to(-10).is_nat());
20130 }
20131
20132 #[test]
20133 fn timestamp_rounding_propagates_nat() {
20134 let nat = Timestamp::nat();
20135 assert!(nat.floor_to(60).is_nat());
20136 assert!(nat.ceil_to(60).is_nat());
20137 assert!(nat.round_to(60).is_nat());
20138 }
20139
20140 #[test]
20141 fn timestamp_rounding_preserves_tz() {
20142 let ts = Timestamp::from_nanos_tz(100, "US/Eastern");
20143 assert_eq!(ts.floor_to(60).tz.as_deref(), Some("US/Eastern"));
20144 assert_eq!(ts.ceil_to(60).tz.as_deref(), Some("US/Eastern"));
20145 assert_eq!(ts.round_to(60).tz.as_deref(), Some("US/Eastern"));
20146 }
20147
20148 #[test]
20151 fn timestamp_floor_to_unit_h_rounds_to_hour() {
20152 let h = Timedelta::NANOS_PER_HOUR;
20153 let twelve_h = h * 12;
20154 let twelve_thirty_four =
20155 twelve_h + Timedelta::NANOS_PER_MIN * 34 + Timedelta::NANOS_PER_SEC * 56;
20156 let ts = Timestamp::from_nanos(twelve_thirty_four);
20157 assert_eq!(ts.floor_to_unit("H").nanos, twelve_h);
20158 assert_eq!(ts.floor_to_unit("h").nanos, twelve_h);
20159 assert_eq!(ts.floor_to_unit("hour").nanos, twelve_h);
20160 assert_eq!(ts.floor_to_unit("hours").nanos, twelve_h);
20161 assert_eq!(ts.floor_to_unit("hr").nanos, twelve_h);
20162 }
20163
20164 #[test]
20165 fn timestamp_ceil_to_unit_d_rounds_to_day() {
20166 let h = Timedelta::NANOS_PER_HOUR;
20168 let d = Timedelta::NANOS_PER_DAY;
20169 let twelve_thirty_four = h * 12 + Timedelta::NANOS_PER_MIN * 34;
20170 let ts = Timestamp::from_nanos(twelve_thirty_four);
20171 assert_eq!(ts.ceil_to_unit("D").nanos, d);
20172 assert_eq!(ts.ceil_to_unit("day").nanos, d);
20173 assert_eq!(ts.ceil_to_unit("days").nanos, d);
20174 }
20175
20176 #[test]
20177 fn timestamp_round_to_unit_min_rounds_to_minute() {
20178 let m = Timedelta::NANOS_PER_MIN;
20180 let twelve_thirty_four_thirty_one =
20181 Timedelta::NANOS_PER_HOUR * 12 + m * 34 + Timedelta::NANOS_PER_SEC * 31;
20182 let ts = Timestamp::from_nanos(twelve_thirty_four_thirty_one);
20183 let expected = Timedelta::NANOS_PER_HOUR * 12 + m * 35;
20184 assert_eq!(ts.round_to_unit("min").nanos, expected);
20185 assert_eq!(ts.round_to_unit("T").nanos, expected); assert_eq!(ts.round_to_unit("minute").nanos, expected);
20187 }
20188
20189 #[test]
20190 fn timestamp_floor_ceil_round_aliases_match_unit_methods_li897() {
20191 let ts = Timestamp::from_nanos(
20192 Timedelta::NANOS_PER_HOUR * 12
20193 + Timedelta::NANOS_PER_MIN * 34
20194 + Timedelta::NANOS_PER_SEC * 31,
20195 );
20196
20197 assert_eq!(ts.floor("H"), ts.floor_to_unit("H"));
20198 assert_eq!(ts.ceil("D"), ts.ceil_to_unit("D"));
20199 assert_eq!(ts.round("min"), ts.round_to_unit("min"));
20200 }
20201
20202 #[test]
20203 fn timestamp_normalize_floors_to_day_and_preserves_tz_455op() {
20204 let ts = Timestamp::from_nanos_tz(
20205 Timedelta::NANOS_PER_DAY * 3
20206 + Timedelta::NANOS_PER_HOUR * 12
20207 + Timedelta::NANOS_PER_MIN * 34,
20208 "US/Eastern",
20209 );
20210 let normalized = ts.normalize();
20211
20212 assert_eq!(normalized.nanos, Timedelta::NANOS_PER_DAY * 3);
20213 assert_eq!(normalized.tz.as_deref(), Some("US/Eastern"));
20214 assert!(Timestamp::nat().normalize().is_nat());
20215 for nanos in [
20216 i64::MIN + 1,
20217 -Timedelta::NANOS_PER_DAY - 1,
20218 -Timedelta::NANOS_PER_DAY,
20219 -1,
20220 0,
20221 Timedelta::NANOS_PER_DAY - 1,
20222 Timedelta::NANOS_PER_DAY,
20223 i64::MAX,
20224 ] {
20225 let timestamp = Timestamp::from_nanos(nanos);
20226 assert_eq!(timestamp.normalize(), timestamp.floor_to_unit("D"));
20227 }
20228 }
20229
20230 #[test]
20231 #[ignore = "foreground profile-first A/B"]
20232 fn timestamp_normalize_direct_day_profile_dk721() {
20233 use std::{hint::black_box, time::Instant};
20234
20235 fn former(timestamp: &Timestamp) -> Timestamp {
20236 timestamp.floor_to_unit("D")
20237 }
20238
20239 fn candidate(timestamp: &Timestamp) -> Timestamp {
20240 timestamp.normalize()
20241 }
20242
20243 fn elapsed(input: &[Timestamp], normalize: impl Fn(&Timestamp) -> Timestamp) -> u128 {
20244 let started = Instant::now();
20245 let mut checksum = 0_u64;
20246 for timestamp in input {
20247 let normalized = normalize(black_box(timestamp));
20248 checksum = checksum.rotate_left(7) ^ normalized.nanos as u64;
20249 }
20250 black_box(checksum);
20251 started.elapsed().as_nanos()
20252 }
20253
20254 fn percentile(samples: &mut [u128], percent: usize) -> u128 {
20255 samples.sort_unstable();
20256 let rank = (samples.len() * percent).div_ceil(100).saturating_sub(1);
20257 samples[rank]
20258 }
20259
20260 let parity_cases = [
20261 Timestamp::nat(),
20262 Timestamp::from_nanos(i64::MIN + 1),
20263 Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY - 1),
20264 Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY),
20265 Timestamp::from_nanos(-1),
20266 Timestamp::from_nanos(0),
20267 Timestamp::from_nanos(Timedelta::NANOS_PER_DAY - 1),
20268 Timestamp::from_nanos(Timedelta::NANOS_PER_DAY),
20269 Timestamp::from_nanos(i64::MAX),
20270 Timestamp::from_nanos_tz(-1, "US/Eastern"),
20271 Timestamp::from_nanos_tz(
20272 Timedelta::NANOS_PER_DAY + Timedelta::NANOS_PER_HOUR,
20273 "Asia/Tokyo",
20274 ),
20275 ];
20276 for timestamp in &parity_cases {
20277 assert_eq!(former(timestamp), candidate(timestamp));
20278 assert_eq!(timestamp.normalize(), former(timestamp));
20279 }
20280
20281 const ROWS: usize = 16_384;
20282 const SAMPLES: usize = 20;
20283 let input = (0..ROWS)
20284 .map(|index| {
20285 let day = index as i64 % 4_096 - 2_048;
20286 let offset = ((index as u64).wrapping_mul(6_364_136_223_846_793_005_u64)
20287 % Timedelta::NANOS_PER_DAY as u64) as i64;
20288 Timestamp::from_nanos(day * Timedelta::NANOS_PER_DAY + offset)
20289 })
20290 .collect::<Vec<_>>();
20291 for timestamp in &input {
20292 assert_eq!(former(timestamp), candidate(timestamp));
20293 }
20294
20295 for _ in 0..3 {
20296 black_box(elapsed(&input, former));
20297 black_box(elapsed(&input, candidate));
20298 }
20299
20300 let mut former_ns = Vec::with_capacity(SAMPLES);
20301 let mut candidate_ns = Vec::with_capacity(SAMPLES);
20302 for sample in 0..SAMPLES {
20303 if sample % 2 == 0 {
20304 former_ns.push(elapsed(&input, former));
20305 candidate_ns.push(elapsed(&input, candidate));
20306 } else {
20307 candidate_ns.push(elapsed(&input, candidate));
20308 former_ns.push(elapsed(&input, former));
20309 }
20310 }
20311
20312 let mut former_sorted = former_ns.clone();
20313 let mut candidate_sorted = candidate_ns.clone();
20314 let former_p50 = percentile(&mut former_sorted, 50);
20315 let former_p95 = percentile(&mut former_sorted, 95);
20316 let former_p99 = percentile(&mut former_sorted, 99);
20317 let candidate_p50 = percentile(&mut candidate_sorted, 50);
20318 let candidate_p95 = percentile(&mut candidate_sorted, 95);
20319 let candidate_p99 = percentile(&mut candidate_sorted, 99);
20320 println!(
20321 "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:?}",
20322 former_p50 as f64 / candidate_p50 as f64,
20323 former_p95 as f64 / candidate_p95 as f64,
20324 former_p99 as f64 / candidate_p99 as f64,
20325 );
20326 }
20327
20328 #[test]
20329 fn timestamp_unit_rounding_unknown_unit_returns_nat() {
20330 let ts = Timestamp::from_nanos(100);
20331 assert!(ts.floor_to_unit("fortnight").is_nat());
20332 assert!(ts.ceil_to_unit("century").is_nat());
20333 assert!(ts.round_to_unit("xyz").is_nat());
20334 }
20335
20336 #[test]
20339 fn timestamp_rounding_reads_a_multiple_of_a_unit_3agof() {
20340 let (min, sec) = (Timedelta::NANOS_PER_MIN, Timedelta::NANOS_PER_SEC);
20341 let base = 1_710_460_800 * sec; let ts = Timestamp::from_nanos(base + 13 * Timedelta::NANOS_PER_HOUR + 47 * min + 21 * sec);
20343 let at = |minutes: i64, seconds: i64| base + minutes * min + seconds * sec;
20344 assert_eq!(ts.round("15min").nanos, at(13 * 60 + 45, 0));
20345 assert_eq!(ts.floor("15min").nanos, at(13 * 60 + 45, 0));
20346 assert_eq!(ts.ceil("15min").nanos, at(14 * 60, 0));
20347 assert_eq!(ts.round("30s").nanos, at(13 * 60 + 47, 30));
20348 assert_eq!(ts.ceil("1D").nanos, base + Timedelta::NANOS_PER_DAY);
20349 assert_eq!(ts.floor("7D").nanos, 19_796 * Timedelta::NANOS_PER_DAY);
20352 assert!(ts.round("ME").is_nat());
20354 }
20355
20356 #[test]
20357 fn timestamp_unit_rounding_propagates_nat() {
20358 let nat = Timestamp::nat();
20359 assert!(nat.floor_to_unit("H").is_nat());
20360 assert!(nat.ceil_to_unit("H").is_nat());
20361 assert!(nat.round_to_unit("H").is_nat());
20362 }
20363
20364 #[test]
20365 fn timestamp_unit_rounding_preserves_tz() {
20366 let ts = Timestamp::from_nanos_tz(Timedelta::NANOS_PER_HOUR * 12 + 100, "US/Eastern");
20367 assert_eq!(ts.floor_to_unit("H").tz.as_deref(), Some("US/Eastern"));
20368 assert_eq!(ts.ceil_to_unit("H").tz.as_deref(), Some("US/Eastern"));
20369 assert_eq!(ts.round_to_unit("H").tz.as_deref(), Some("US/Eastern"));
20370 }
20371
20372 #[test]
20373 fn timedelta_unit_to_nanos_is_now_public_and_matches_pandas_aliases() {
20374 assert_eq!(
20376 Timedelta::unit_to_nanos("W"),
20377 Some(Timedelta::NANOS_PER_WEEK)
20378 );
20379 assert_eq!(
20380 Timedelta::unit_to_nanos("D"),
20381 Some(Timedelta::NANOS_PER_DAY)
20382 );
20383 assert_eq!(
20384 Timedelta::unit_to_nanos("H"),
20385 Some(Timedelta::NANOS_PER_HOUR)
20386 );
20387 assert_eq!(
20388 Timedelta::unit_to_nanos("min"),
20389 Some(Timedelta::NANOS_PER_MIN)
20390 );
20391 assert_eq!(
20392 Timedelta::unit_to_nanos("s"),
20393 Some(Timedelta::NANOS_PER_SEC)
20394 );
20395 assert_eq!(
20396 Timedelta::unit_to_nanos("ms"),
20397 Some(Timedelta::NANOS_PER_MILLI)
20398 );
20399 assert_eq!(
20400 Timedelta::unit_to_nanos("us"),
20401 Some(Timedelta::NANOS_PER_MICRO)
20402 );
20403 assert_eq!(Timedelta::unit_to_nanos("ns"), Some(1));
20404 assert_eq!(Timedelta::unit_to_nanos(""), Some(Timedelta::NANOS_PER_DAY));
20406 assert_eq!(Timedelta::unit_to_nanos("century"), None);
20408 }
20409
20410 #[test]
20411 fn timestamp_isoformat_basic() {
20412 let ts = Timestamp::from_nanos(0);
20413 assert_eq!(ts.isoformat(), "1970-01-01T00:00:00");
20414
20415 let ts_utc = Timestamp::from_nanos_tz(0, "UTC");
20416 assert_eq!(ts_utc.isoformat(), "1970-01-01T00:00:00+00:00");
20417
20418 let ts_fixed_offset = Timestamp::from_nanos_tz(0, "UTC+05:30");
20419 assert_eq!(
20420 ts_fixed_offset.isoformat(),
20421 "1970-01-01T05:30:00+05:30",
20422 "a fixed-offset timestamp must render local wall time rather than a UTC instant with an annotation"
20423 );
20424
20425 let ts_tz = Timestamp::from_nanos_tz(
20426 Timedelta::NANOS_PER_DAY
20427 + Timedelta::NANOS_PER_HOUR * 14
20428 + Timedelta::NANOS_PER_MIN * 30,
20429 "America/New_York",
20430 );
20431 assert!(ts_tz.isoformat().contains("1970-01-02T14:30:00"));
20432 assert!(ts_tz.isoformat().contains("[America/New_York]"));
20433
20434 assert_eq!(Timestamp::nat().isoformat(), "NaT");
20435 }
20436
20437 #[test]
20438 fn timestamp_isoformat_pre_epoch_subsecond_uses_floor_day_263m5() {
20439 assert_eq!(
20440 Timestamp::from_nanos(-1).isoformat(),
20441 "1969-12-31T23:59:59.999999999"
20442 );
20443 assert_eq!(
20444 Timestamp::from_nanos(-Timedelta::NANOS_PER_SEC).isoformat(),
20445 "1969-12-31T23:59:59"
20446 );
20447 assert_eq!(
20448 Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY).isoformat(),
20449 "1969-12-31T00:00:00"
20450 );
20451 assert_eq!(
20452 Timestamp::from_nanos_tz(-1, "UTC").isoformat(),
20453 "1969-12-31T23:59:59.999999999+00:00"
20454 );
20455 }
20456
20457 #[test]
20458 fn timestamp_isoformat_preserves_nanosecond_fraction_4r99y() {
20459 assert_eq!(
20460 Timestamp::from_nanos(123_456_789).isoformat(),
20461 "1970-01-01T00:00:00.123456789"
20462 );
20463 assert_eq!(
20464 Timestamp::from_nanos(123_456_000).isoformat(),
20465 "1970-01-01T00:00:00.123456"
20466 );
20467 assert_eq!(
20468 Timestamp::from_nanos(123_000_000).isoformat(),
20469 "1970-01-01T00:00:00.123000"
20470 );
20471 assert_eq!(
20472 Timestamp::from_nanos_tz(1, "UTC").isoformat(),
20473 "1970-01-01T00:00:00.000000001+00:00"
20474 );
20475 }
20476
20477 fn timestamp_isoformat_former_q8g50(timestamp: &Timestamp) -> String {
20478 if timestamp.is_nat() {
20479 return "NaT".to_owned();
20480 }
20481 let base = Timestamp::from_nanos(timestamp.nanos).isoformat();
20482 match ×tamp.tz {
20483 Some(tz) if tz == "UTC" => format!("{base}+00:00"),
20484 Some(tz) => format!("{base}[{tz}]"),
20485 None => base,
20486 }
20487 }
20488
20489 #[test]
20490 fn timestamp_isoformat_one_buffer_matches_former_q8g50() {
20491 let nanos = [
20492 Timestamp::NAT,
20493 -Timedelta::NANOS_PER_DAY - 1,
20494 -Timedelta::NANOS_PER_SEC,
20495 -1,
20496 0,
20497 1,
20498 123_456_000,
20499 123_456_789,
20500 i64::MAX,
20501 ];
20502 let timezones = [
20503 None,
20504 Some("UTC"),
20505 Some("America/New_York"),
20506 Some(""),
20507 Some("Etc/Γ"),
20508 ];
20509 for value in nanos {
20510 for timezone in timezones {
20511 let timestamp = Timestamp {
20512 nanos: value,
20513 tz: timezone.map(str::to_owned),
20514 };
20515 assert_eq!(
20516 timestamp.isoformat(),
20517 timestamp_isoformat_former_q8g50(×tamp),
20518 "nanos={value} timezone={timezone:?}"
20519 );
20520 }
20521 }
20522 }
20523
20524 #[test]
20525 #[ignore = "foreground release A/B only"]
20526 fn timestamp_isoformat_one_buffer_ab_q8g50() {
20527 use std::{hint::black_box, time::Instant};
20528
20529 const ITEMS: usize = 8_192;
20530 const SAMPLES: usize = 10;
20531
20532 fn elapsed(values: &[Timestamp], render: fn(&Timestamp) -> String) -> u128 {
20533 let started = Instant::now();
20534 let mut checksum = 0usize;
20535 for timestamp in black_box(values) {
20536 checksum = checksum.wrapping_add(black_box(render(black_box(timestamp))).len());
20537 }
20538 black_box(checksum);
20539 started.elapsed().as_nanos()
20540 }
20541
20542 let values = (0..ITEMS)
20543 .map(|idx| {
20544 let nanos = (idx as i64 - ITEMS as i64 / 2) * 1_000_123_456_789;
20545 let timezone = if idx.is_multiple_of(2) {
20546 "UTC"
20547 } else {
20548 "America/New_York"
20549 };
20550 Timestamp::from_nanos_tz(nanos, timezone)
20551 })
20552 .collect::<Vec<_>>();
20553 for timestamp in &values {
20554 assert_eq!(
20555 timestamp.isoformat(),
20556 timestamp_isoformat_former_q8g50(timestamp)
20557 );
20558 }
20559
20560 black_box(elapsed(&values, timestamp_isoformat_former_q8g50));
20561 black_box(elapsed(&values, Timestamp::isoformat));
20562
20563 let mut former_ns = Vec::with_capacity(SAMPLES);
20564 let mut one_buffer_ns = Vec::with_capacity(SAMPLES);
20565 for sample in 0..SAMPLES {
20566 if sample.is_multiple_of(2) {
20567 former_ns.push(elapsed(&values, timestamp_isoformat_former_q8g50));
20568 one_buffer_ns.push(elapsed(&values, Timestamp::isoformat));
20569 } else {
20570 one_buffer_ns.push(elapsed(&values, Timestamp::isoformat));
20571 former_ns.push(elapsed(&values, timestamp_isoformat_former_q8g50));
20572 }
20573 }
20574 former_ns.sort_unstable();
20575 one_buffer_ns.sort_unstable();
20576 let former_p50 = former_ns[SAMPLES / 2];
20577 let one_buffer_p50 = one_buffer_ns[SAMPLES / 2];
20578 println!(
20579 "timestamp_isoformat_one_buffer_ab items={ITEMS} samples={SAMPLES} former_p50_ns={former_p50} one_buffer_p50_ns={one_buffer_p50} speedup={:.6}x",
20580 former_p50 as f64 / one_buffer_p50 as f64
20581 );
20582 println!("former_samples_ns={former_ns:?}");
20583 println!("one_buffer_samples_ns={one_buffer_ns:?}");
20584 }
20585
20586 #[test]
20587 fn timestamp_strftime_basic() {
20588 let ts = Timestamp::from_nanos(
20589 Timedelta::NANOS_PER_DAY * 365
20590 + Timedelta::NANOS_PER_HOUR * 9
20591 + Timedelta::NANOS_PER_MIN * 15,
20592 );
20593 assert_eq!(ts.strftime("%Y-%m-%d"), "1971-01-01");
20594 assert_eq!(ts.strftime("%H:%M:%S"), "09:15:00");
20595 assert_eq!(ts.strftime("%Y/%m/%d %H:%M"), "1971/01/01 09:15");
20596 assert_eq!(ts.strftime("%%Y|%%%m|%Q|%|λ"), "%Y|%01|%Q|%|λ");
20599 assert_eq!(Timestamp::nat().strftime("%Y-%m-%d"), "NaT");
20600 }
20601
20602 #[test]
20603 fn strftime_follows_python_directives_and_zones() {
20604 let ts = Timestamp::from_nanos(
20607 Timedelta::NANOS_PER_DAY * 365
20608 + Timedelta::NANOS_PER_HOUR * 9
20609 + Timedelta::NANOS_PER_MIN * 15,
20610 );
20611 assert_eq!(
20612 ts.strftime("%-d %_m %^a %e %k %l %P %C %g %D %F %T %R %r %h %n %t|"),
20613 "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|"
20614 );
20615 assert_eq!(
20616 ts.strftime("%a %A %b %B %c|%x %X|%I %p %j %U %W %w %y"),
20617 "Fri Friday Jan January Fri Jan 1 09:15:00 1971|01/01/71 09:15:00|09 AM 001 00 00 5 71"
20618 );
20619 let sunday = Timestamp::parse("2021-01-03").expect("date");
20621 assert_eq!(sunday.strftime("%G-%V-%u %U %W %j"), "2020-53-7 01 00 003");
20622 let fraction = Timestamp::parse("2024-03-05 14:07:09.123456789").expect("ts");
20624 assert_eq!(fraction.strftime("%f|%z|%Z|abc%"), "123456|||abc%");
20625 let eastern = Timestamp::from_nanos_tz(fraction.nanos, "US/Eastern");
20627 assert_eq!(
20628 eastern.strftime("%Y-%m-%d %H:%M %z %Z"),
20629 "2024-03-05 09:07 -0500 EST"
20630 );
20631 assert_eq!(
20632 crate::strftime_in_zone(fraction.nanos, "%H:%M %z", Some("+05:30")),
20633 "19:37 +0530"
20634 );
20635 }
20636
20637 #[test]
20638 fn timestamp_strftime_floors_pre_epoch_instants_1pmlp() {
20639 let apollo = Timestamp::parse("1969-07-20T20:17:40").unwrap();
20640 assert_eq!(
20641 apollo.strftime("%Y-%m-%d %H:%M:%S.%f"),
20642 "1969-07-20 20:17:40.000000"
20643 );
20644
20645 let one_ns_before_epoch = Timestamp::from_nanos(-1);
20648 assert_eq!(
20649 one_ns_before_epoch.strftime("%Y-%m-%d %H:%M:%S.%f"),
20650 "1969-12-31 23:59:59.999999"
20651 );
20652 }
20653
20654 #[test]
20655 #[ignore = "foreground normal-release attribution harness"]
20656 fn timestamp_strftime_one_buffer_profile_8qzbo() {
20657 use std::{hint::black_box, time::Instant};
20658
20659 const ITEMS: usize = 8_192;
20660 const SAMPLES: usize = 10;
20661 const FORMAT: &str = "%Y-%m-%d %H:%M:%S.%f|%Y%m%d|%%Y|λ%Q";
20662
20663 fn former(timestamp: &Timestamp, format: &str) -> String {
20664 if timestamp.is_nat() {
20665 return "NaT".to_string();
20666 }
20667 let total_secs = timestamp.nanos / Timedelta::NANOS_PER_SEC;
20668 let sub_nanos = timestamp.nanos.rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
20669
20670 let days_since_epoch = total_secs / 86400;
20671 let secs_of_day = (total_secs % 86400 + 86400) % 86400;
20672 let days = days_since_epoch + 719_468;
20673 let era = (if days >= 0 { days } else { days - 146_096 }) / 146_097;
20674 let doe = days - era * 146_097;
20675 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
20676 let y = yoe + era * 400;
20677 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
20678 let mp = (5 * doy + 2) / 153;
20679 let d = doy - (153 * mp + 2) / 5 + 1;
20680 let m = if mp < 10 { mp + 3 } else { mp - 9 };
20681 let year = if m <= 2 { y + 1 } else { y };
20682 let hour = secs_of_day / 3600;
20683 let minute = (secs_of_day % 3600) / 60;
20684 let second = secs_of_day % 60;
20685 let micros = sub_nanos / 1000;
20686
20687 format
20688 .replace("%Y", &format!("{year:04}"))
20689 .replace("%m", &format!("{m:02}"))
20690 .replace("%d", &format!("{d:02}"))
20691 .replace("%H", &format!("{hour:02}"))
20692 .replace("%M", &format!("{minute:02}"))
20693 .replace("%S", &format!("{second:02}"))
20694 .replace("%f", &format!("{micros:06}"))
20695 }
20696
20697 fn elapsed(timestamps: &[Timestamp], formatter: fn(&Timestamp, &str) -> String) -> u128 {
20698 let started = Instant::now();
20699 let mut digest = 0_usize;
20700 for timestamp in timestamps {
20701 let value = formatter(black_box(timestamp), black_box(FORMAT));
20702 digest = digest.wrapping_add(value.len());
20703 digest ^= usize::from(value.as_bytes().first().copied().unwrap_or_default());
20704 black_box(value);
20705 }
20706 black_box(digest);
20707 started.elapsed().as_nanos()
20708 }
20709
20710 fn percentile(samples: &mut [u128], pct: usize) -> u128 {
20711 samples.sort_unstable();
20712 let rank = (samples.len() * pct).div_ceil(100).saturating_sub(1);
20713 samples[rank]
20714 }
20715
20716 let edge_timestamps = [
20717 Timestamp::nat(),
20718 Timestamp::from_nanos(i64::MIN + 1),
20719 Timestamp::from_nanos(-1_234_567_890),
20720 Timestamp::from_nanos(0),
20721 Timestamp::from_nanos(1_735_732_800_123_456_789),
20722 Timestamp::from_nanos(i64::MAX),
20723 ];
20724 let edge_formats = [
20725 "",
20726 "%Y-%m-%d %H:%M:%S.%f",
20727 "%Y%Y%m%m%d%d%H%H%M%M%S%S%f%f",
20728 "%%Y|%%%m|%Q|%|λ",
20729 FORMAT,
20730 ];
20731 for timestamp in &edge_timestamps {
20732 for format in edge_formats {
20733 assert_eq!(former(timestamp, format), timestamp.strftime(format));
20734 }
20735 }
20736
20737 let timestamps = (0..ITEMS)
20738 .map(|index| {
20739 let centered = index as i64 - ITEMS as i64 / 2;
20740 Timestamp::from_nanos(centered * 987_654_321_123_456)
20741 })
20742 .collect::<Vec<_>>();
20743 for timestamp in ×tamps {
20744 assert_eq!(former(timestamp, FORMAT), timestamp.strftime(FORMAT));
20745 }
20746
20747 black_box(elapsed(×tamps, former));
20748 black_box(elapsed(×tamps, Timestamp::strftime));
20749
20750 let mut former_samples = Vec::with_capacity(SAMPLES);
20751 let mut public_samples = Vec::with_capacity(SAMPLES);
20752 for sample in 0..SAMPLES {
20753 if sample.is_multiple_of(2) {
20754 former_samples.push(elapsed(×tamps, former));
20755 public_samples.push(elapsed(×tamps, Timestamp::strftime));
20756 } else {
20757 public_samples.push(elapsed(×tamps, Timestamp::strftime));
20758 former_samples.push(elapsed(×tamps, former));
20759 }
20760 }
20761 let former_p50 = percentile(&mut former_samples, 50);
20762 let former_p95 = percentile(&mut former_samples, 95);
20763 let public_p50 = percentile(&mut public_samples, 50);
20764 let public_p95 = percentile(&mut public_samples, 95);
20765 println!(
20766 "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}",
20767 former_p50 as f64 / public_p50 as f64,
20768 former_p95 as f64 / public_p95 as f64,
20769 );
20770 println!("TIMESTAMP_STRFTIME_AB former_samples_ns={former_samples:?}");
20771 println!("TIMESTAMP_STRFTIME_AB public_samples_ns={public_samples:?}");
20772 }
20773
20774 #[test]
20775 fn timestamp_day_name_and_month_name() {
20776 let ts = Timestamp::from_nanos(0);
20777 assert_eq!(ts.day_name(), "Thursday");
20778 assert_eq!(ts.month_name(), "January");
20779
20780 let ts2 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 365);
20781 assert_eq!(ts2.day_name(), "Friday");
20782 assert_eq!(ts2.month_name(), "January");
20783
20784 assert_eq!(Timestamp::nat().day_name(), "NaT");
20785 assert_eq!(Timestamp::nat().month_name(), "NaT");
20786 }
20787
20788 #[test]
20789 fn timestamp_replace_validates_components_zw0y2() {
20790 let ts = Timestamp::parse("2024-01-15T10:30:45.123456789").unwrap();
20791 let replaced = ts.replace(
20792 Some(2024),
20793 Some(2),
20794 Some(29),
20795 Some(23),
20796 Some(59),
20797 Some(58),
20798 Some(987_654),
20799 Some(321),
20800 );
20801 assert_eq!(replaced.year(), Some(2024));
20802 assert_eq!(replaced.month(), Some(2));
20803 assert_eq!(replaced.day(), Some(29));
20804 assert_eq!(replaced.hour(), Some(23));
20805 assert_eq!(replaced.minute(), Some(59));
20806 assert_eq!(replaced.second(), Some(58));
20807 assert_eq!(replaced.microsecond(), Some(987_654));
20808 assert_eq!(replaced.nanosecond(), Some(321));
20809
20810 let tz = Timestamp::from_nanos_tz(ts.nanos, "UTC");
20811 assert_eq!(
20812 tz.replace(None, Some(2), Some(29), None, None, None, None, None)
20813 .tz
20814 .as_deref(),
20815 Some("UTC")
20816 );
20817
20818 assert!(
20819 ts.replace(None, Some(13), None, None, None, None, None, None)
20820 .is_nat()
20821 );
20822 assert!(
20823 ts.replace(Some(2023), Some(2), Some(29), None, None, None, None, None)
20824 .is_nat()
20825 );
20826 assert!(
20827 ts.replace(None, None, None, Some(24), None, None, None, None)
20828 .is_nat()
20829 );
20830 assert!(
20831 ts.replace(None, None, None, None, Some(60), None, None, None)
20832 .is_nat()
20833 );
20834 assert!(
20835 ts.replace(None, None, None, None, None, Some(60), None, None)
20836 .is_nat()
20837 );
20838 assert!(
20839 ts.replace(None, None, None, None, None, None, Some(1_000_000), None)
20840 .is_nat()
20841 );
20842 assert!(
20843 ts.replace(None, None, None, None, None, None, None, Some(1_000))
20844 .is_nat()
20845 );
20846 assert!(
20847 Timestamp::nat()
20848 .replace(Some(2024), Some(1), Some(1), None, None, None, None, None)
20849 .is_nat()
20850 );
20851 }
20852
20853 #[test]
20860 fn timestamp_replace_returns_nat_on_nanosecond_overflow_dzz6x() {
20861 let ts = Timestamp::parse("2024-01-15T10:30:45.123456789").unwrap();
20862
20863 for year in [3000, 10_000, 300_000, i64::MAX / 400] {
20864 let out = ts.replace(Some(year), None, None, None, None, None, None, None);
20865 assert!(
20866 out.is_nat(),
20867 "replace(year={year}) is unrepresentable in i64 ns and must be \
20868 NaT, got nanos={:?} (year {:?}) — this is the silent wrap",
20869 out.nanos,
20870 out.year()
20871 );
20872 }
20873 for year in [-3000, -100_000, i64::MIN / 400] {
20874 let out = ts.replace(Some(year), None, None, None, None, None, None, None);
20875 assert!(out.is_nat(), "replace(year={year}) must be NaT");
20876 }
20877
20878 let in_range = ts.replace(
20883 Some(2262),
20884 Some(1),
20885 Some(1),
20886 Some(0),
20887 Some(0),
20888 Some(0),
20889 Some(0),
20890 Some(0),
20891 );
20892 assert!(
20893 !in_range.is_nat(),
20894 "2262-01-01 is representable and must survive"
20895 );
20896 assert_eq!(in_range.year(), Some(2262));
20897 assert!(
20898 ts.replace(
20899 Some(2263),
20900 Some(12),
20901 Some(31),
20902 Some(23),
20903 Some(59),
20904 Some(59),
20905 Some(999_999),
20906 Some(999)
20907 )
20908 .is_nat(),
20909 "end of 2263 exceeds the i64 ns axis and must be NaT"
20910 );
20911
20912 let unchanged = ts.replace(
20916 Some(1999),
20917 Some(6),
20918 Some(30),
20919 Some(12),
20920 Some(1),
20921 Some(2),
20922 Some(3),
20923 Some(4),
20924 );
20925 assert_eq!(unchanged.year(), Some(1999));
20926 assert_eq!(unchanged.month(), Some(6));
20927 assert_eq!(unchanged.day(), Some(30));
20928 assert_eq!(unchanged.hour(), Some(12));
20929 assert_eq!(unchanged.minute(), Some(1));
20930 assert_eq!(unchanged.second(), Some(2));
20931 assert_eq!(unchanged.microsecond(), Some(3));
20932 assert_eq!(unchanged.nanosecond(), Some(4));
20933 let tz = Timestamp::from_nanos_tz(ts.nanos, "UTC");
20934 assert_eq!(
20935 tz.replace(Some(1999), None, None, None, None, None, None, None)
20936 .tz
20937 .as_deref(),
20938 Some("UTC")
20939 );
20940 }
20941
20942 #[test]
20943 fn timestamp_component_accessors() {
20944 let ts = Timestamp::from_nanos(0);
20945 assert_eq!(ts.year(), Some(1970));
20946 assert_eq!(ts.month(), Some(1));
20947 assert_eq!(ts.day(), Some(1));
20948 assert_eq!(ts.hour(), Some(0));
20949 assert_eq!(ts.minute(), Some(0));
20950 assert_eq!(ts.second(), Some(0));
20951 assert_eq!(ts.microsecond(), Some(0));
20952 assert_eq!(ts.nanosecond(), Some(0));
20953
20954 let ts2 = Timestamp::from_nanos(
20955 Timedelta::NANOS_PER_DAY * 365
20956 + Timedelta::NANOS_PER_HOUR * 14
20957 + Timedelta::NANOS_PER_MIN * 30
20958 + Timedelta::NANOS_PER_SEC * 45
20959 + 123_456_789,
20960 );
20961 assert_eq!(ts2.year(), Some(1971));
20962 assert_eq!(ts2.month(), Some(1));
20963 assert_eq!(ts2.day(), Some(1));
20964 assert_eq!(ts2.hour(), Some(14));
20965 assert_eq!(ts2.minute(), Some(30));
20966 assert_eq!(ts2.second(), Some(45));
20967 assert_eq!(ts2.microsecond(), Some(123456));
20968 assert_eq!(ts2.nanosecond(), Some(789));
20969
20970 assert_eq!(Timestamp::nat().year(), None);
20971 assert_eq!(Timestamp::nat().month(), None);
20972 assert_eq!(Timestamp::nat().day(), None);
20973 }
20974
20975 #[test]
20976 fn timestamp_dayofweek_dayofyear_quarter() {
20977 let ts = Timestamp::from_nanos(0);
20978 assert_eq!(ts.dayofweek(), Some(3));
20979 assert_eq!(ts.weekday(), Some(3));
20980 assert_eq!(ts.dayofyear(), Some(1));
20981 assert_eq!(ts.quarter(), Some(1));
20982
20983 let ts2 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 90);
20984 assert_eq!(ts2.quarter(), Some(2));
20985
20986 let ts3 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 365);
20987 assert_eq!(ts3.dayofyear(), Some(1));
20988 assert_eq!(ts3.dayofweek(), Some(4));
20989
20990 assert_eq!(Timestamp::nat().dayofweek(), None);
20991 assert_eq!(Timestamp::nat().dayofyear(), None);
20992 assert_eq!(Timestamp::nat().quarter(), None);
20993 }
20994
20995 #[test]
20996 fn timestamp_is_boundary_methods() {
20997 let jan1 = Timestamp::from_nanos(0);
20998 assert_eq!(jan1.is_leap_year(), Some(false));
20999 assert_eq!(jan1.is_month_start(), Some(true));
21000 assert_eq!(jan1.is_month_end(), Some(false));
21001 assert_eq!(jan1.is_quarter_start(), Some(true));
21002 assert_eq!(jan1.is_quarter_end(), Some(false));
21003 assert_eq!(jan1.is_year_start(), Some(true));
21004 assert_eq!(jan1.is_year_end(), Some(false));
21005
21006 let dec31 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 364);
21007 assert_eq!(dec31.is_month_start(), Some(false));
21008 assert_eq!(dec31.is_month_end(), Some(true));
21009 assert_eq!(dec31.is_quarter_end(), Some(true));
21010 assert_eq!(dec31.is_year_end(), Some(true));
21011
21012 assert_eq!(Timestamp::nat().is_leap_year(), None);
21013 assert_eq!(Timestamp::nat().is_month_start(), None);
21014 }
21015
21016 #[test]
21017 fn timestamp_days_in_month() {
21018 let jan = Timestamp::from_nanos(0);
21019 assert_eq!(jan.days_in_month(), Some(31));
21020 assert_eq!(jan.daysinmonth(), Some(31));
21021
21022 let feb_non_leap = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 31);
21023 assert_eq!(feb_non_leap.days_in_month(), Some(28));
21024
21025 assert_eq!(Timestamp::nat().days_in_month(), None);
21026 }
21027
21028 #[test]
21029 fn timestamp_weekofyear() {
21030 let jan1 = Timestamp::from_nanos(0);
21031 assert_eq!(jan1.weekofyear(), Some(1));
21032 assert_eq!(jan1.week(), Some(1));
21033
21034 let jan8 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 7);
21035 assert_eq!(jan8.weekofyear(), Some(2));
21036
21037 assert_eq!(Timestamp::nat().weekofyear(), None);
21038 assert_eq!(Timestamp::nat().week(), None);
21039 }
21040
21041 #[test]
21042 fn timestamp_weekofyear_iso_53_week_boundaries() {
21043 fn week_of(date_days: i64) -> Option<i64> {
21046 Timestamp::from_nanos(date_days * Timedelta::NANOS_PER_DAY).weekofyear()
21047 }
21048 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)); }
21062
21063 #[test]
21064 fn iso_weeks_in_year_53_week_years() {
21065 use super::iso_weeks_in_year;
21066 for y in [2004, 2009, 2015, 2020, 2026] {
21068 assert_eq!(iso_weeks_in_year(y), 53, "{y} should have 53 ISO weeks");
21069 }
21070 for y in [2018, 2019, 2021, 2022, 2023, 2024] {
21071 assert_eq!(iso_weeks_in_year(y), 52, "{y} should have 52 ISO weeks");
21072 }
21073 }
21074
21075 #[test]
21076 fn timestamp_to_unit() {
21077 let ts = Timestamp::from_nanos(1_000_000_000);
21078 assert_eq!(ts.to_unit("ns"), Some(1_000_000_000));
21079 assert_eq!(ts.to_unit("us"), Some(1_000_000));
21080 assert_eq!(ts.to_unit("ms"), Some(1_000));
21081 assert_eq!(ts.to_unit("s"), Some(1));
21082 assert_eq!(ts.to_unit("invalid"), None);
21083
21084 assert_eq!(Timestamp::nat().to_unit("ns"), None);
21085 }
21086
21087 #[test]
21088 fn timestamp_toordinal() {
21089 let nanos_2026_01_01 = 19723_i64 * 24 * 60 * 60 * 1_000_000_000;
21092 let ts = Timestamp::from_nanos(nanos_2026_01_01);
21093 assert_eq!(ts.toordinal(), Some(738886));
21094
21095 assert_eq!(Timestamp::nat().toordinal(), None);
21097 }
21098
21099 #[test]
21100 fn timestamp_fromordinal() {
21101 let nanos_2026_01_01 = 19723_i64 * 24 * 60 * 60 * 1_000_000_000;
21104 let ts_orig = Timestamp::from_nanos(nanos_2026_01_01);
21105 let ordinal = ts_orig.toordinal().unwrap();
21106
21107 let ts = Timestamp::fromordinal(ordinal);
21109 assert_eq!(ts.year(), ts_orig.year());
21110 assert_eq!(ts.month(), ts_orig.month());
21111 assert_eq!(ts.day(), ts_orig.day());
21112
21113 let nat = Timestamp::fromordinal(0);
21115 assert!(nat.is_nat());
21116 }
21117
21118 #[test]
21119 fn timestamp_fromordinal_guards_nanosecond_overflow_ycvrd() {
21120 const EPOCH_ORDINAL: i64 = 719_163;
21121 let max_day_offset = i64::MAX / Timedelta::NANOS_PER_DAY;
21122 let max_valid_ordinal = EPOCH_ORDINAL + max_day_offset;
21123
21124 let max_valid = Timestamp::fromordinal(max_valid_ordinal);
21125 assert!(!max_valid.is_nat());
21126 assert_eq!(max_valid.nanos, max_day_offset * Timedelta::NANOS_PER_DAY);
21127
21128 assert!(Timestamp::fromordinal(max_valid_ordinal + 1).is_nat());
21129 assert!(Timestamp::fromordinal(i64::MAX).is_nat());
21130 }
21131
21132 #[test]
21133 fn timestamp_ordinal_matches_seeded_epoch_oracle_l2f0p() {
21134 const EPOCH_ORDINAL: i64 = 719_163;
21135 const DAY: i64 = Timedelta::NANOS_PER_DAY;
21136
21137 fn next(seed: &mut u64) -> u64 {
21138 *seed = seed
21139 .wrapping_mul(3202034522624059733)
21140 .wrapping_add(4354685564936845319);
21141 *seed
21142 }
21143
21144 fn assert_ordinal_case(case: usize, day_offset: i64, subday_nanos: i64) {
21145 let nanos = day_offset.saturating_mul(DAY).saturating_add(subday_nanos);
21146 let ts = Timestamp::from_nanos(nanos);
21147 let expected_day_offset = nanos.div_euclid(DAY);
21148 let expected_ordinal = EPOCH_ORDINAL + expected_day_offset;
21149
21150 assert_eq!(
21151 ts.toordinal(),
21152 Some(expected_ordinal),
21153 "case {case}: toordinal"
21154 );
21155
21156 let midnight = Timestamp::fromordinal(expected_ordinal);
21157 assert_eq!(
21158 midnight.nanos,
21159 expected_day_offset * DAY,
21160 "case {case}: fromordinal nanos"
21161 );
21162 assert_eq!(
21163 midnight.toordinal(),
21164 Some(expected_ordinal),
21165 "case {case}: fromordinal roundtrip"
21166 );
21167 }
21168
21169 assert_eq!(Timestamp::nat().toordinal(), None);
21170 assert!(Timestamp::fromordinal(0).is_nat());
21171 assert!(Timestamp::fromordinal(-1).is_nat());
21172
21173 assert_ordinal_case(usize::MAX, -1, DAY - 1);
21174 assert_ordinal_case(usize::MAX - 1, 0, -1);
21175 assert_ordinal_case(usize::MAX - 2, 19_723, 0);
21176
21177 let mut seed = 0x1f20_f0d1_0a11_0d1e_u64;
21178 for case in 0..260 {
21179 let day_offset = (next(&mut seed) % 40_001) as i64 - 10_000;
21180 let subday_nanos = match case % 7 {
21181 0 => 0,
21182 1 => DAY - 1,
21183 2 => -1,
21184 _ => (next(&mut seed) % (2 * DAY as u64 - 1)) as i64 - (DAY - 1),
21185 };
21186 assert_ordinal_case(case, day_offset, subday_nanos);
21187 }
21188 }
21189
21190 #[test]
21197 fn timestamp_parse_rejects_unrepresentable_years_94o1u() {
21198 for s in [
21199 "300000-01-01",
21200 "10000000-06-15T12:30:45",
21201 "999999999-01-01",
21202 "-300000-01-01",
21203 "-99999999-12-31T23:59:59",
21204 ] {
21205 let got = Timestamp::parse(s);
21206 assert!(
21207 got.is_err(),
21208 "parse({s:?}) is unrepresentable in i64 ns and must be Err, got {:?} \
21209 — this is the silent wrap",
21210 got.map(|ts| (ts.nanos, ts.year()))
21211 );
21212 }
21213
21214 let ok = Timestamp::parse("2262-01-01").expect("2262-01-01 is representable");
21217 assert_eq!(ok.year(), Some(2262));
21218 assert!(
21219 Timestamp::parse("2263-12-31T23:59:59").is_err(),
21220 "end of 2263 exceeds the i64 ns axis and must be Err"
21221 );
21222
21223 assert_eq!(Timestamp::parse("2024-01-15").unwrap().year(), Some(2024));
21227 assert_eq!(
21228 Timestamp::parse("2024-01-15T10:30:45").unwrap().hour(),
21229 Some(10)
21230 );
21231 assert_eq!(
21232 Timestamp::parse("2024-01-15 10:30:45").unwrap().minute(),
21233 Some(30)
21234 );
21235 assert_eq!(
21236 Timestamp::parse("2024-01-15T10:30:45.123456789")
21237 .unwrap()
21238 .nanosecond(),
21239 Some(789)
21240 );
21241 assert_eq!(
21242 Timestamp::parse("2024-01-15T00:00:00Z").unwrap().year(),
21243 Some(2024)
21244 );
21245 assert_eq!(Timestamp::parse("1900-01-01").unwrap().year(), Some(1900));
21247 }
21248
21249 #[test]
21250 fn timestamp_parse_iso8601_date_only() {
21251 let ts = Timestamp::parse("2024-01-15").unwrap();
21252 assert_eq!(ts.year(), Some(2024));
21253 assert_eq!(ts.month(), Some(1));
21254 assert_eq!(ts.day(), Some(15));
21255 assert_eq!(ts.hour(), Some(0));
21256 assert_eq!(ts.minute(), Some(0));
21257 assert_eq!(ts.second(), Some(0));
21258 }
21259
21260 #[test]
21261 fn timestamp_parse_iso8601_datetime() {
21262 let ts = Timestamp::parse("2024-01-15T10:30:45").unwrap();
21263 assert_eq!(ts.year(), Some(2024));
21264 assert_eq!(ts.month(), Some(1));
21265 assert_eq!(ts.day(), Some(15));
21266 assert_eq!(ts.hour(), Some(10));
21267 assert_eq!(ts.minute(), Some(30));
21268 assert_eq!(ts.second(), Some(45));
21269 }
21270
21271 #[test]
21272 fn timestamp_parse_space_separator() {
21273 let ts = Timestamp::parse("2024-01-15 10:30:45").unwrap();
21274 assert_eq!(ts.year(), Some(2024));
21275 assert_eq!(ts.hour(), Some(10));
21276 }
21277
21278 #[test]
21279 fn timestamp_parse_with_fractional_seconds() {
21280 let ts = Timestamp::parse("2024-01-15T10:30:45.123456789").unwrap();
21281 assert_eq!(ts.second(), Some(45));
21282 assert_eq!(ts.microsecond(), Some(123456));
21283 assert_eq!(ts.nanosecond(), Some(789));
21284 }
21285
21286 #[test]
21287 fn timestamp_parse_utc_timezone() {
21288 let ts = Timestamp::parse("2024-01-15T10:30:45Z").unwrap();
21289 assert_eq!(ts.tz, Some("UTC".to_string()));
21290 }
21291
21292 #[test]
21293 fn timestamp_parse_offset_timezone() {
21294 let ts = Timestamp::parse("2024-01-15T10:30:45+05:30").unwrap();
21295 assert_eq!(ts.tz, Some("+05:30".to_string()));
21296 let utc = |text: &str| Timestamp::parse(text).unwrap().nanos;
21299 assert_eq!(ts.nanos, utc("2024-01-15T05:00:45"));
21300
21301 let ts = Timestamp::parse("2024-01-15T10:30:45-05:30").unwrap();
21302 assert_eq!(ts.tz, Some("-05:30".to_string()));
21303 assert_eq!(ts.nanos, utc("2024-01-15T16:00:45"));
21304 assert_eq!(
21306 Timestamp::parse("2024-01-15T10:30:45Z").unwrap().nanos,
21307 utc("2024-01-15T10:30:45")
21308 );
21309 }
21310
21311 #[test]
21312 fn timestamp_parse_rejects_invalid_timezone_offsets_0v676() {
21313 assert!(Timestamp::parse("2024-01-15T10:30:45+bad").is_err());
21314 assert!(Timestamp::parse("2024-01-15T10:30:45+0500").is_err());
21315 assert!(Timestamp::parse("2024-01-15T10:30:45+24:00").is_err());
21316 assert!(Timestamp::parse("2024-01-15T10:30:45+05:60").is_err());
21317 assert!(Timestamp::parse("2024-01-15T10:30:45-25:00").is_err());
21318 }
21319
21320 #[test]
21321 fn timestamp_parse_nat() {
21322 let ts = Timestamp::parse("NaT").unwrap();
21323 assert!(ts.is_nat());
21324 let ts2 = Timestamp::parse("nat").unwrap();
21325 assert!(ts2.is_nat());
21326 }
21327
21328 #[test]
21329 fn timestamp_parse_invalid() {
21330 assert!(Timestamp::parse("not a date").is_err());
21331 assert!(Timestamp::parse("2024-13-01").is_err()); assert!(Timestamp::parse("2024-01-32").is_err()); }
21334
21335 #[test]
21336 fn timestamp_parse_rejects_invalid_fractional_seconds_87se2() {
21337 assert!(Timestamp::parse("2024-01-15T10:30:45.").is_err());
21338 assert!(Timestamp::parse("2024-01-15T10:30:45.abc").is_err());
21339 assert!(Timestamp::parse("2024-01-15T10:30:45.-1").is_err());
21340 assert!(Timestamp::parse("2024-01-15T10:30:45.123").is_err());
21341 assert!(Timestamp::parse("2024-01-15T10:30:45.123456789x").is_err());
21342
21343 let ts = Timestamp::parse("2024-01-15T10:30:45.123456789987").unwrap();
21344 assert_eq!(ts.second(), Some(45));
21345 assert_eq!(ts.microsecond(), Some(123456));
21346 assert_eq!(ts.nanosecond(), Some(789));
21347 }
21348
21349 #[test]
21350 #[ignore = "foreground profile-first A/B"]
21351 fn timestamp_parse_fraction_digit_fold_profile_pdiku() {
21352 use std::{hint::black_box, time::Instant};
21353
21354 const CALLS: usize = 131_072;
21355 const SAMPLES: usize = 12;
21356 type ParsedTime = Option<(u32, u32, u32, u64)>;
21357 const VALID: [&str; 16] = [
21358 "00:00:00.0",
21359 "01:02:03.1",
21360 "02:03:04.01",
21361 "03:04:05.001",
21362 "04:05:06.0001",
21363 "05:06:07.00001",
21364 "06:07:08.000001",
21365 "07:08:09.0000001",
21366 "08:09:10.00000001",
21367 "09:10:11.000000001",
21368 "10:11:12.123456789",
21369 "11:12:13.999999999",
21370 "12:13:14.123456789987",
21371 "13:14:15.000000000001",
21372 "14:15:16.101010101010",
21373 "23:59:59.987654321234",
21374 ];
21375
21376 #[inline(never)]
21377 fn former(s: &str) -> ParsedTime {
21378 let (time_str, frac_str) = match s.split_once('.') {
21379 Some((time, frac)) => (time, Some(frac)),
21380 None => (s, None),
21381 };
21382 let parts: Vec<&str> = time_str.split(':').collect();
21383 if parts.is_empty() || parts.len() > 3 {
21384 return None;
21385 }
21386 let hour: u32 = parts.first().and_then(|p| p.parse().ok())?;
21387 let minute: u32 = parts.get(1).and_then(|p| p.parse().ok()).unwrap_or(0);
21388 let second: u32 = parts.get(2).and_then(|p| p.parse().ok()).unwrap_or(0);
21389
21390 if hour > 23 || minute > 59 || second > 59 {
21391 return None;
21392 }
21393
21394 let nanos = match frac_str {
21395 None => 0,
21396 Some(frac) => {
21397 if frac.is_empty() || !frac.bytes().all(|b| b.is_ascii_digit()) {
21398 return None;
21399 }
21400 let truncated = &frac[..frac.len().min(9)];
21401 let padded = format!("{truncated:0<9}");
21402 padded.parse::<u64>().ok()?
21403 }
21404 };
21405
21406 Some((hour, minute, second, nanos))
21407 }
21408
21409 #[inline(never)]
21410 fn candidate(s: &str) -> ParsedTime {
21411 Timestamp::parse_time(s)
21412 }
21413
21414 fn elapsed(inputs: &[&str], parser: fn(&str) -> ParsedTime) -> u128 {
21415 let started = Instant::now();
21416 for input in black_box(inputs) {
21417 black_box(parser(black_box(*input)));
21418 }
21419 started.elapsed().as_nanos()
21420 }
21421
21422 fn percentile(samples: &[u128], percent: usize) -> u128 {
21423 let mut sorted = samples.to_vec();
21424 sorted.sort_unstable();
21425 let rank = (sorted.len() * percent).div_ceil(100).saturating_sub(1);
21426 sorted[rank]
21427 }
21428
21429 let invalid = [
21430 "",
21431 "24:00:00.1",
21432 "12:60:00.1",
21433 "12:00:60.1",
21434 "12:00:00.",
21435 "12:00:00.abc",
21436 "12:00:00.-1",
21437 "12:00:00.123",
21438 "12:00:00.123456789x",
21439 "12:00:00.1.2",
21440 "12:00:00:01.1",
21441 ];
21442 for input in VALID.iter().chain(invalid.iter()) {
21443 assert_eq!(candidate(input), former(input), "input={input:?}");
21444 }
21445
21446 let inputs = (0..CALLS)
21447 .map(|index| VALID[index % VALID.len()])
21448 .collect::<Vec<_>>();
21449 for _ in 0..2 {
21450 black_box(elapsed(&inputs, former));
21451 black_box(elapsed(&inputs, candidate));
21452 }
21453
21454 let mut former_ns = Vec::with_capacity(SAMPLES);
21455 let mut candidate_ns = Vec::with_capacity(SAMPLES);
21456 for sample in 0..SAMPLES {
21457 if sample.is_multiple_of(2) {
21458 former_ns.push(elapsed(&inputs, former));
21459 candidate_ns.push(elapsed(&inputs, candidate));
21460 } else {
21461 candidate_ns.push(elapsed(&inputs, candidate));
21462 former_ns.push(elapsed(&inputs, former));
21463 }
21464 }
21465
21466 let former_p50 = percentile(&former_ns, 50);
21467 let former_p95 = percentile(&former_ns, 95);
21468 let former_p99 = percentile(&former_ns, 99);
21469 let candidate_p50 = percentile(&candidate_ns, 50);
21470 let candidate_p95 = percentile(&candidate_ns, 95);
21471 let candidate_p99 = percentile(&candidate_ns, 99);
21472 println!(
21473 "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:?}",
21474 former_p50 as f64 / candidate_p50 as f64,
21475 former_p95 as f64 / candidate_p95 as f64,
21476 former_p99 as f64 / candidate_p99 as f64,
21477 );
21478 }
21479
21480 #[test]
21481 fn timestamp_parse_matches_seeded_iso_component_oracle_1u7a0() {
21482 fn next(seed: &mut u64) -> u64 {
21483 *seed = seed
21484 .wrapping_mul(3935559000370003845)
21485 .wrapping_add(2691343689449507681);
21486 *seed
21487 }
21488
21489 fn leap(year: i64) -> bool {
21490 (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
21491 }
21492
21493 fn month_len(year: i64, month: u32) -> u32 {
21494 match month {
21495 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
21496 4 | 6 | 9 | 11 => 30,
21497 2 if leap(year) => 29,
21498 2 => 28,
21499 _ => 0,
21500 }
21501 }
21502
21503 struct Components {
21504 year: i64,
21505 month: u32,
21506 day: u32,
21507 hour: u32,
21508 minute: u32,
21509 second: u32,
21510 nanos: u64,
21511 }
21512
21513 fn assert_components(case: usize, text: &str, expected: Components) {
21514 let ts = Timestamp::parse(text).expect("seeded valid timestamp");
21515 let Components {
21516 year,
21517 month,
21518 day,
21519 hour,
21520 minute,
21521 second,
21522 nanos,
21523 } = expected;
21524 assert_eq!(ts.year(), Some(year), "case {case}: year");
21525 assert_eq!(ts.month(), Some(month as i64), "case {case}: month");
21526 assert_eq!(ts.day(), Some(day as i64), "case {case}: day");
21527 assert_eq!(ts.hour(), Some(hour as i64), "case {case}: hour");
21528 assert_eq!(ts.minute(), Some(minute as i64), "case {case}: minute");
21529 assert_eq!(ts.second(), Some(second as i64), "case {case}: second");
21530 assert_eq!(
21531 ts.microsecond(),
21532 Some((nanos / 1000) as i64),
21533 "case {case}: microsecond"
21534 );
21535 assert_eq!(
21536 ts.nanosecond(),
21537 Some((nanos % 1000) as i64),
21538 "case {case}: nanosecond"
21539 );
21540 }
21541
21542 assert!(Timestamp::parse("NaT").expect("NaT parses").is_nat());
21543 assert!(
21544 Timestamp::parse("nAt")
21545 .expect("mixed-case NaT parses")
21546 .is_nat()
21547 );
21548 assert!(Timestamp::parse("1900-02-29").is_err());
21549 assert!(Timestamp::parse("2001-04-31").is_err());
21550 assert!(Timestamp::parse("2024-00-15").is_err());
21551
21552 assert_components(
21553 usize::MAX,
21554 "2000-02-29",
21555 Components {
21556 year: 2000,
21557 month: 2,
21558 day: 29,
21559 hour: 0,
21560 minute: 0,
21561 second: 0,
21562 nanos: 0,
21563 },
21564 );
21565 assert_components(
21566 usize::MAX - 1,
21567 "2024-02-29T23:59:59.000000001",
21568 Components {
21569 year: 2024,
21570 month: 2,
21571 day: 29,
21572 hour: 23,
21573 minute: 59,
21574 second: 59,
21575 nanos: 1,
21576 },
21577 );
21578
21579 let mut seed = 0x15e0_1d50_1f0a_cade_u64;
21580 for case in 0..260 {
21581 let year = 1900 + (next(&mut seed) % 201) as i64;
21582 let month = 1 + (next(&mut seed) % 12) as u32;
21583 let day = 1 + (next(&mut seed) % month_len(year, month) as u64) as u32;
21584 let hour = (next(&mut seed) % 24) as u32;
21585 let minute = (next(&mut seed) % 60) as u32;
21586 let second = (next(&mut seed) % 60) as u32;
21587 let nanos = next(&mut seed) % 1_000_000_000;
21588
21589 match case % 4 {
21590 0 => {
21591 let text = format!("{year:04}-{month:02}-{day:02}");
21592 assert_components(
21593 case,
21594 &text,
21595 Components {
21596 year,
21597 month,
21598 day,
21599 hour: 0,
21600 minute: 0,
21601 second: 0,
21602 nanos: 0,
21603 },
21604 );
21605 }
21606 1 => {
21607 let text =
21608 format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}");
21609 assert_components(
21610 case,
21611 &text,
21612 Components {
21613 year,
21614 month,
21615 day,
21616 hour,
21617 minute,
21618 second,
21619 nanos: 0,
21620 },
21621 );
21622 }
21623 2 => {
21624 let text =
21625 format!("{year:04}-{month:02}-{day:02} {hour:02}:{minute:02}:{second:02}");
21626 assert_components(
21627 case,
21628 &text,
21629 Components {
21630 year,
21631 month,
21632 day,
21633 hour,
21634 minute,
21635 second,
21636 nanos: 0,
21637 },
21638 );
21639 }
21640 _ => {
21641 let text = format!(
21642 "{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}.{nanos:09}"
21643 );
21644 assert_components(
21645 case,
21646 &text,
21647 Components {
21648 year,
21649 month,
21650 day,
21651 hour,
21652 minute,
21653 second,
21654 nanos,
21655 },
21656 );
21657 }
21658 }
21659 }
21660 }
21661
21662 #[test]
21663 fn period_parse_annual() {
21664 let p = Period::parse("2024").unwrap();
21665 assert_eq!(p.freq(), PeriodFreq::ANNUAL);
21666 assert_eq!(p.ordinal(), 2024 - 1970);
21667 }
21668
21669 #[test]
21670 fn period_parse_quarterly() {
21671 let p = Period::parse("2024Q1").unwrap();
21672 assert_eq!(p.freq(), PeriodFreq::QUARTERLY);
21673 assert_eq!(p.ordinal(), (2024 - 1970) * 4);
21674
21675 let p2 = Period::parse("2024q3").unwrap();
21676 assert_eq!(p2.freq(), PeriodFreq::QUARTERLY);
21677 assert_eq!(p2.ordinal(), (2024 - 1970) * 4 + 2);
21678 }
21679
21680 #[test]
21681 fn period_parse_monthly() {
21682 let p = Period::parse("2024-01").unwrap();
21683 assert_eq!(p.freq(), PeriodFreq::Monthly);
21684 assert_eq!(p.ordinal(), (2024 - 1970) * 12);
21685
21686 let p2 = Period::parse("2024-12").unwrap();
21687 assert_eq!(p2.freq(), PeriodFreq::Monthly);
21688 assert_eq!(p2.ordinal(), (2024 - 1970) * 12 + 11);
21689 }
21690
21691 #[test]
21692 fn period_parse_nat() {
21693 let p = Period::parse("NaT").unwrap();
21694 assert_eq!(p.ordinal(), i64::MIN);
21695 }
21696
21697 #[test]
21698 fn period_parse_invalid() {
21699 assert!(Period::parse("not a period").is_err());
21700 assert!(Period::parse("2024Q5").is_err()); assert!(Period::parse("2024-13").is_err()); }
21703
21704 #[test]
21705 fn interval_parse_basic() {
21706 let i = Interval::parse("[0, 1]").unwrap();
21707 assert_eq!(i.left, 0.0);
21708 assert_eq!(i.right, 1.0);
21709 assert_eq!(i.closed, IntervalClosed::Both);
21710
21711 let i2 = Interval::parse("(0, 1)").unwrap();
21712 assert_eq!(i2.left, 0.0);
21713 assert_eq!(i2.right, 1.0);
21714 assert_eq!(i2.closed, IntervalClosed::Neither);
21715
21716 let i3 = Interval::parse("[0, 1)").unwrap();
21717 assert_eq!(i3.closed, IntervalClosed::Left);
21718
21719 let i4 = Interval::parse("(0, 1]").unwrap();
21720 assert_eq!(i4.closed, IntervalClosed::Right);
21721 }
21722
21723 #[test]
21724 fn interval_parse_floats() {
21725 let i = Interval::parse("[-1.5, 2.5)").unwrap();
21726 assert_eq!(i.left, -1.5);
21727 assert_eq!(i.right, 2.5);
21728 assert_eq!(i.closed, IntervalClosed::Left);
21729 }
21730
21731 #[test]
21732 fn interval_parse_invalid() {
21733 assert!(Interval::parse("invalid").is_err());
21734 assert!(Interval::parse("[0]").is_err());
21735 assert!(Interval::parse("0, 1").is_err()); }
21737
21738 fn interval_parse_error_profile(s: &str) -> super::TypeError {
21739 super::TypeError::ValueNotParseable {
21740 value: s.to_string(),
21741 target: "Interval".to_string(),
21742 }
21743 }
21744
21745 #[inline(never)]
21746 fn interval_parse_former_profile(s: &str) -> Result<Interval, super::TypeError> {
21747 let s = std::hint::black_box(s).trim();
21748 if s.len() < 5 {
21749 return Err(interval_parse_error_profile(s));
21750 }
21751
21752 let first_char = s.chars().next().unwrap();
21753 let last_char = s.chars().last().unwrap();
21754 let left_closed = match first_char {
21755 '[' => true,
21756 '(' => false,
21757 _ => return Err(interval_parse_error_profile(s)),
21758 };
21759 let right_closed = match last_char {
21760 ']' => true,
21761 ')' => false,
21762 _ => return Err(interval_parse_error_profile(s)),
21763 };
21764 let closed = match (left_closed, right_closed) {
21765 (true, true) => IntervalClosed::Both,
21766 (true, false) => IntervalClosed::Left,
21767 (false, true) => IntervalClosed::Right,
21768 (false, false) => IntervalClosed::Neither,
21769 };
21770
21771 let inner = &s[1..s.len() - 1];
21772 let parts: Vec<&str> = inner.split(',').collect();
21773 if parts.len() != 2 {
21774 return Err(interval_parse_error_profile(s));
21775 }
21776 let left = parts[0]
21777 .trim()
21778 .parse()
21779 .map_err(|_| interval_parse_error_profile(s))?;
21780 let right = parts[1]
21781 .trim()
21782 .parse()
21783 .map_err(|_| interval_parse_error_profile(s))?;
21784 Ok(Interval::new(left, right, closed))
21785 }
21786
21787 #[inline(never)]
21788 fn interval_parse_split_once_profile(s: &str) -> Result<Interval, super::TypeError> {
21789 Interval::parse(std::hint::black_box(s))
21790 }
21791
21792 fn assert_interval_parse_profile_parity(s: &str) {
21793 match (
21794 interval_parse_former_profile(s),
21795 interval_parse_split_once_profile(s),
21796 ) {
21797 (Ok(former), Ok(candidate)) => {
21798 assert_eq!(former.left.to_bits(), candidate.left.to_bits(), "left: {s}");
21799 assert_eq!(
21800 former.right.to_bits(),
21801 candidate.right.to_bits(),
21802 "right: {s}"
21803 );
21804 assert_eq!(former.closed, candidate.closed, "closed: {s}");
21805 }
21806 (Err(former), Err(candidate)) => assert_eq!(former, candidate, "error: {s}"),
21807 (former, candidate) => assert_eq!(
21808 former.is_ok(),
21809 candidate.is_ok(),
21810 "parse result mismatch for {s}: {former:?} != {candidate:?}"
21811 ),
21812 }
21813 }
21814
21815 #[inline(never)]
21816 fn measure_interval_parser_profile(
21817 parser: fn(&str) -> Result<Interval, super::TypeError>,
21818 inputs: &[&str],
21819 rounds: usize,
21820 ) -> u128 {
21821 use std::{hint::black_box, time::Instant};
21822
21823 let started = Instant::now();
21824 let mut checksum = 0_u64;
21825 for _ in 0..rounds {
21826 for input in inputs {
21827 let parsed = parser(black_box(input)).expect("profile input must parse");
21828 let closed = match parsed.closed {
21829 IntervalClosed::Left => 1_u64,
21830 IntervalClosed::Right => 2,
21831 IntervalClosed::Both => 3,
21832 IntervalClosed::Neither => 4,
21833 };
21834 checksum = checksum
21835 .wrapping_add(parsed.left.to_bits().rotate_left(7))
21836 .wrapping_add(parsed.right.to_bits().rotate_right(11))
21837 .wrapping_add(closed);
21838 black_box(parsed);
21839 }
21840 }
21841 black_box(checksum);
21842 started.elapsed().as_nanos()
21843 }
21844
21845 #[test]
21846 #[ignore = "release-only attribution probe for br-frankenpandas-81jjv"]
21847 fn profile_interval_parse_endpoint_split_ab_81jjv() {
21848 const VALID: [&str; 8] = [
21849 "[0, 1]",
21850 "(-0.0, 0.0]",
21851 " [ -1.5e3 , 2.75E-4 ) ",
21852 "(NaN, -0]",
21853 "[-inf, inf)",
21854 "[9.25, -7.5]",
21855 "(4.9406564584124654e-324, 1.7976931348623157e308)",
21856 "[-42, 17.125)",
21857 ];
21858 const INVALID: [&str; 12] = [
21859 "invalid",
21860 "[0]",
21861 "0, 1",
21862 "[0 1]",
21863 "[0, 1, 2]",
21864 "[0, 1,]",
21865 "[0,,1]",
21866 "[, 1]",
21867 "[0, ]",
21868 "{0, 1}",
21869 "[0, 1}",
21870 " ⟦0, 1⟧ ",
21871 ];
21872 const ROUNDS: usize = 16_384;
21873 const SAMPLES: usize = 10;
21874
21875 for input in VALID.iter().chain(INVALID.iter()) {
21876 assert_interval_parse_profile_parity(input);
21877 }
21878 for _ in 0..2 {
21879 measure_interval_parser_profile(interval_parse_former_profile, &VALID, ROUNDS);
21880 measure_interval_parser_profile(interval_parse_split_once_profile, &VALID, ROUNDS);
21881 }
21882
21883 let mut former_ns = Vec::with_capacity(SAMPLES);
21884 let mut candidate_ns = Vec::with_capacity(SAMPLES);
21885 for sample in 0..SAMPLES {
21886 if sample % 2 == 0 {
21887 former_ns.push(measure_interval_parser_profile(
21888 interval_parse_former_profile,
21889 &VALID,
21890 ROUNDS,
21891 ));
21892 candidate_ns.push(measure_interval_parser_profile(
21893 interval_parse_split_once_profile,
21894 &VALID,
21895 ROUNDS,
21896 ));
21897 } else {
21898 candidate_ns.push(measure_interval_parser_profile(
21899 interval_parse_split_once_profile,
21900 &VALID,
21901 ROUNDS,
21902 ));
21903 former_ns.push(measure_interval_parser_profile(
21904 interval_parse_former_profile,
21905 &VALID,
21906 ROUNDS,
21907 ));
21908 }
21909 }
21910 former_ns.sort_unstable();
21911 candidate_ns.sort_unstable();
21912 let former_p50 = former_ns[SAMPLES / 2];
21913 let candidate_p50 = candidate_ns[SAMPLES / 2];
21914 let former_p95 = former_ns[SAMPLES - 1];
21915 let candidate_p95 = candidate_ns[SAMPLES - 1];
21916 println!("PROFILE_INTERVAL_PARSE_FORMER_NS={former_ns:?}");
21917 println!("PROFILE_INTERVAL_PARSE_CANDIDATE_NS={candidate_ns:?}");
21918 println!(
21919 "PROFILE_INTERVAL_PARSE_P50_RATIO={:.6}",
21920 former_p50 as f64 / candidate_p50 as f64
21921 );
21922 println!(
21923 "PROFILE_INTERVAL_PARSE_P95_RATIO={:.6}",
21924 former_p95 as f64 / candidate_p95 as f64
21925 );
21926 }
21927}
21928
21929#[cfg(test)]
21935mod float64_nullable_qkqfb {
21936 use super::{DType, NullKind, Scalar, cast_scalar, common_dtype};
21937
21938 #[test]
21949 fn the_two_float_flavours_have_different_missing_markers_qkqfb() {
21950 assert_eq!(
21951 Scalar::missing_for_dtype(DType::Float64Nullable),
21952 Scalar::Null(NullKind::Null),
21953 "the extension lane stores pd.NA"
21954 );
21955 assert_eq!(
21956 Scalar::missing_for_dtype(DType::Float64),
21957 Scalar::Null(NullKind::NaN),
21958 "the numpy lane stores a real NaN"
21959 );
21960 assert_ne!(
21963 Scalar::missing_for_dtype(DType::Float64Nullable),
21964 Scalar::missing_for_dtype(DType::Float64),
21965 );
21966 }
21967
21968 #[test]
21972 fn spelling_is_pandas_spelling_qkqfb() {
21973 assert_eq!(DType::Float64Nullable.name(), "Float64");
21974 assert_eq!(DType::Float64.name(), "float64");
21975 assert_ne!(DType::Float64Nullable.name(), DType::Float64.name());
21976 }
21977
21978 #[test]
21985 fn serde_round_trips_and_does_not_collide_with_numpy_float64_qkqfb() {
21986 let ext = serde_json::to_string(&DType::Float64Nullable).expect("serialize");
21987 let numpy = serde_json::to_string(&DType::Float64).expect("serialize");
21988 assert_eq!(ext, "\"Float64\"");
21989 assert_eq!(numpy, "\"float64\"");
21990 assert_ne!(ext, numpy);
21991
21992 assert_eq!(
21993 serde_json::from_str::<DType>(&ext).expect("deserialize"),
21994 DType::Float64Nullable
21995 );
21996 assert_eq!(
21997 serde_json::from_str::<DType>(&numpy).expect("deserialize"),
21998 DType::Float64
21999 );
22000 }
22001
22002 #[test]
22005 fn predicates_place_it_in_the_right_families_qkqfb() {
22006 assert!(DType::Float64Nullable.is_floating());
22007 assert!(DType::Float64Nullable.is_numeric());
22008 assert!(DType::Float64Nullable.is_any_real_numeric());
22009 assert!(DType::Float64Nullable.is_nullable());
22010 assert!(DType::Float64Nullable.is_extension());
22011 assert!(!DType::Float64Nullable.is_integer());
22014 assert!(!DType::Float64Nullable.is_signed_integer());
22015 assert!(!DType::Float64Nullable.is_bool());
22016 assert_eq!(DType::Float64Nullable.kind(), 'f');
22019 assert_eq!(DType::Float64Nullable.kind(), DType::Float64.kind());
22020 assert_eq!(DType::Float64Nullable.itemsize(), 8);
22021 }
22022
22023 #[test]
22026 fn nullable_pairing_is_an_involution_qkqfb() {
22027 assert_eq!(DType::Float64.to_nullable(), DType::Float64Nullable);
22028 assert_eq!(DType::Float64Nullable.to_non_nullable(), DType::Float64);
22029 assert_eq!(DType::Float64Nullable.to_nullable(), DType::Float64Nullable);
22031 assert_eq!(DType::Float64.to_non_nullable(), DType::Float64);
22032 assert_eq!(DType::Int64.to_nullable(), DType::Int64Nullable);
22034 assert_eq!(DType::Bool.to_nullable(), DType::BoolNullable);
22035 }
22036
22037 #[test]
22047 fn the_nullable_float_absorbs_every_numeric_flavour_qkqfb() {
22048 for other in [
22049 DType::Float64,
22050 DType::Int64,
22051 DType::Int64Nullable,
22052 DType::Bool,
22053 DType::BoolNullable,
22054 DType::Float64Nullable,
22055 ] {
22056 assert_eq!(
22057 common_dtype(DType::Float64Nullable, other.clone()),
22058 Ok(DType::Float64Nullable),
22059 "Float64Nullable + {other:?}"
22060 );
22061 assert_eq!(
22065 common_dtype(other.clone(), DType::Float64Nullable),
22066 Ok(DType::Float64Nullable),
22067 "{other:?} + Float64Nullable"
22068 );
22069 }
22070 assert_eq!(
22072 common_dtype(DType::Null, DType::Float64Nullable),
22073 Ok(DType::Float64Nullable)
22074 );
22075 }
22076
22077 #[test]
22086 fn casts_preserve_values_and_convert_only_the_marker_qkqfb() {
22087 let present = Scalar::Float64(1.5);
22088 assert_eq!(
22089 cast_scalar(&present, DType::Float64Nullable),
22090 Ok(Scalar::Float64(1.5))
22091 );
22092 assert_eq!(
22093 cast_scalar(&Scalar::Float64(1.5), DType::Float64),
22094 Ok(Scalar::Float64(1.5))
22095 );
22096 assert_eq!(
22098 cast_scalar(&Scalar::Int64(1), DType::Float64Nullable),
22099 Ok(Scalar::Float64(1.0))
22100 );
22101 assert_eq!(
22102 cast_scalar(&Scalar::Bool(true), DType::Float64Nullable),
22103 Ok(Scalar::Float64(1.0))
22104 );
22105
22106 assert_eq!(
22109 cast_scalar(&Scalar::Null(NullKind::NaN), DType::Float64Nullable),
22110 Ok(Scalar::Null(NullKind::Null)),
22111 "numpy NaN entering an extension lane becomes pd.NA"
22112 );
22113 assert_eq!(
22114 cast_scalar(&Scalar::Null(NullKind::Null), DType::Float64),
22115 Ok(Scalar::Null(NullKind::NaN)),
22116 "pd.NA entering a numpy lane becomes NaN"
22117 );
22118 }
22119
22120 #[test]
22130 fn int64nullable_plus_numpy_float_answers_the_nullable_float_qkqfb() {
22131 assert_eq!(
22132 common_dtype(DType::Int64Nullable, DType::Float64),
22133 Ok(DType::Float64Nullable)
22134 );
22135 assert_eq!(
22136 common_dtype(DType::Float64, DType::Int64Nullable),
22137 Ok(DType::Float64Nullable)
22138 );
22139 }
22140
22141 #[test]
22149 fn boolnullable_plus_numpy_float_answers_the_nullable_float_qkqfb() {
22150 assert_eq!(
22151 common_dtype(DType::BoolNullable, DType::Float64),
22152 Ok(DType::Float64Nullable)
22153 );
22154 assert_eq!(
22155 common_dtype(DType::Bool, DType::Float64),
22156 Ok(DType::Float64),
22157 "numpy bool + numpy float stays entirely on the numpy side"
22158 );
22159 }
22160
22161 #[test]
22172 fn the_nullable_float_flip_is_associative_on_its_witness_triple_qkqfb() {
22173 let (bn, i64n, f64d) = (DType::BoolNullable, DType::Int64, DType::Float64);
22174
22175 let left = common_dtype(
22176 common_dtype(bn.clone(), i64n.clone()).unwrap(),
22177 f64d.clone(),
22178 )
22179 .unwrap();
22180 let right = common_dtype(bn, common_dtype(i64n, f64d).unwrap()).unwrap();
22181
22182 assert_eq!(left, right, "promotion order must not change the result");
22183 assert_eq!(left, DType::Float64Nullable);
22184 }
22185}
22186
22187#[cfg(test)]
22192mod sparse_dtype_pandas_name_3gxc6 {
22193 use super::{DType, Scalar, SparseDType};
22194
22195 fn name(value_dtype: DType, fill: Scalar) -> String {
22196 SparseDType::new(value_dtype, fill)
22197 .expect("sparse descriptor")
22198 .pandas_name()
22199 }
22200
22201 #[test]
22204 fn int64_fill_zero_is_the_fixture_row() {
22205 assert_eq!(name(DType::Int64, Scalar::Int64(0)), "Sparse[int64, 0]");
22206 }
22207
22208 #[test]
22211 fn the_fill_value_is_actually_rendered() {
22212 assert_eq!(name(DType::Int64, Scalar::Int64(7)), "Sparse[int64, 7]");
22213 assert_ne!(
22214 name(DType::Int64, Scalar::Int64(0)),
22215 name(DType::Int64, Scalar::Int64(7)),
22216 "two different fills must not collapse to one name"
22217 );
22218 }
22219
22220 #[test]
22222 fn float64_nan_fill_is_lowercase_nan() {
22223 assert_eq!(
22224 name(DType::Float64, Scalar::Float64(f64::NAN)),
22225 "Sparse[float64, nan]"
22226 );
22227 }
22228
22229 #[test]
22232 fn float64_zero_fill_keeps_its_trailing_point_zero() {
22233 assert_eq!(
22234 name(DType::Float64, Scalar::Float64(0.0)),
22235 "Sparse[float64, 0.0]"
22236 );
22237 assert_ne!(
22238 name(DType::Float64, Scalar::Float64(0.0)),
22239 name(DType::Int64, Scalar::Int64(0)),
22240 "float64 and int64 zero fills are different dtypes"
22241 );
22242 }
22243
22244 #[test]
22246 fn bool_fill_uses_python_capitalisation() {
22247 assert_eq!(
22248 name(DType::Bool, Scalar::Bool(false)),
22249 "Sparse[bool, False]"
22250 );
22251 assert_eq!(name(DType::Bool, Scalar::Bool(true)), "Sparse[bool, True]");
22252 }
22253
22254 #[test]
22257 fn utf8_subtype_renders_as_object() {
22258 let rendered = name(DType::Utf8, Scalar::Null(crate::NullKind::NaN));
22259 assert!(
22260 rendered.starts_with("Sparse[object, "),
22261 "expected an object subtype, got {rendered}"
22262 );
22263 }
22264
22265 #[test]
22268 fn no_constructible_descriptor_renders_the_bare_name() {
22269 for (dtype, fill) in [
22270 (DType::Int64, Scalar::Int64(0)),
22271 (DType::Float64, Scalar::Float64(1.5)),
22272 (DType::Bool, Scalar::Bool(true)),
22273 (DType::Utf8, Scalar::Utf8("x".to_owned())),
22274 ] {
22275 let rendered = name(dtype.clone(), fill);
22276 assert_ne!(rendered, "Sparse", "bare name regressed for {dtype:?}");
22277 assert!(
22278 rendered.starts_with("Sparse[") && rendered.ends_with(']'),
22279 "malformed sparse name {rendered}"
22280 );
22281 }
22282 }
22283
22284 #[test]
22285 fn test_dtype_from_str_and_display() {
22286 use std::str::FromStr;
22287
22288 use crate::DType;
22289
22290 assert_eq!(DType::from_str("int64").unwrap(), DType::Int64);
22291 assert_eq!(DType::from_str("Int64").unwrap(), DType::Int64Nullable);
22292 assert_eq!(DType::from_str("float64").unwrap(), DType::Float64);
22293 assert_eq!(DType::from_str("Float64").unwrap(), DType::Float64Nullable);
22294 assert_eq!(DType::from_str("bool").unwrap(), DType::Bool);
22295 assert_eq!(DType::from_str("boolean").unwrap(), DType::BoolNullable);
22296 assert_eq!(DType::from_str("string").unwrap(), DType::Utf8);
22297 assert_eq!(DType::from_str("category").unwrap(), DType::Categorical);
22298 assert_eq!(
22299 DType::from_str("timedelta64[ns]").unwrap(),
22300 DType::Timedelta64
22301 );
22302 assert_eq!(
22303 DType::from_str("datetime64[ns]").unwrap(),
22304 DType::Datetime64 { tz: None }
22305 );
22306 assert_eq!(
22307 DType::from_str("datetime64[ns, UTC]").unwrap(),
22308 DType::Datetime64 {
22309 tz: Some("UTC".to_string())
22310 }
22311 );
22312 assert_eq!(DType::from_str("period").unwrap(), DType::Period);
22313 assert_eq!(DType::from_str("interval").unwrap(), DType::Interval);
22314 assert_eq!(DType::from_str("sparse").unwrap(), DType::Sparse);
22315
22316 assert_eq!(format!("{}", DType::Int64), "int64");
22317 assert_eq!(
22318 format!(
22319 "{}",
22320 DType::Datetime64 {
22321 tz: Some("UTC".to_string())
22322 }
22323 ),
22324 "datetime64[ns, UTC]"
22325 );
22326 }
22327
22328 #[test]
22329 fn test_api_types_inspection_and_infer_dtype() {
22330 use crate::{
22331 DType, Scalar,
22332 api::types::{
22333 infer_dtype, is_bool_dtype, is_categorical_dtype, is_datetime64_any_dtype,
22334 is_dtype_equal, is_extension_array_dtype, is_float_dtype, is_int64_dtype,
22335 is_integer_dtype, is_interval_dtype, is_numeric_dtype, is_object_dtype,
22336 is_period_dtype, is_scalar, is_signed_integer_dtype, is_sparse, is_string_dtype,
22337 is_timedelta64_dtype, is_unsigned_integer_dtype, pandas_dtype,
22338 },
22339 };
22340
22341 assert!(is_numeric_dtype(&DType::Int64));
22342 assert!(is_numeric_dtype(&DType::Float64));
22343 assert!(!is_numeric_dtype(&DType::Utf8));
22344 assert!(!is_numeric_dtype(&DType::Bool));
22345
22346 assert!(is_integer_dtype(&DType::Int64));
22347 assert!(is_integer_dtype(&DType::Int64Nullable));
22348 assert!(!is_integer_dtype(&DType::Float64));
22349
22350 assert!(is_int64_dtype(&DType::Int64));
22351 assert!(is_int64_dtype(&DType::Int64Nullable));
22352 assert!(!is_int64_dtype(&DType::Float64));
22353
22354 assert!(is_object_dtype(&DType::Utf8));
22355 assert!(!is_object_dtype(&DType::Int64));
22356
22357 assert!(is_dtype_equal(&DType::Int64, &DType::Int64));
22358 assert!(is_dtype_equal(&"int64", &DType::Int64));
22359 assert!(!is_dtype_equal(&DType::Int64, &DType::Float64));
22360
22361 assert!(is_signed_integer_dtype(&DType::Int64));
22362 assert!(!is_unsigned_integer_dtype(&DType::Int64));
22363
22364 assert!(is_float_dtype(&DType::Float64));
22365 assert!(is_bool_dtype(&DType::Bool));
22366 assert!(is_string_dtype(&DType::Utf8));
22367 assert!(is_datetime64_any_dtype(&DType::Datetime64 { tz: None }));
22368 assert!(is_timedelta64_dtype(&DType::Timedelta64));
22369 assert!(is_categorical_dtype(&DType::Categorical));
22370 assert!(is_period_dtype(&DType::Period));
22371 assert!(is_interval_dtype(&DType::Interval));
22372 assert!(is_sparse(&DType::Sparse));
22373 assert!(is_extension_array_dtype(&DType::Categorical));
22374 assert!(is_scalar(&Scalar::Int64(42)));
22375
22376 assert_eq!(pandas_dtype("float64").unwrap(), DType::Float64);
22377 assert!(pandas_dtype("invalid_dtype_xyz").is_err());
22378
22379 let ints = vec![Scalar::Int64(1), Scalar::Int64(2)];
22380 assert_eq!(infer_dtype(&ints, true), "integer");
22381
22382 let floats = vec![Scalar::Float64(1.0), Scalar::Float64(2.5)];
22383 assert_eq!(infer_dtype(&floats, true), "floating");
22384
22385 let bools = vec![Scalar::Bool(true), Scalar::Bool(false)];
22386 assert_eq!(infer_dtype(&bools, true), "boolean");
22387
22388 let strings = vec![Scalar::Utf8("a".to_string()), Scalar::Utf8("b".to_string())];
22389 assert_eq!(infer_dtype(&strings, true), "string");
22390
22391 let mixed = vec![Scalar::Int64(1), Scalar::Utf8("a".to_string())];
22392 assert_eq!(infer_dtype(&mixed, true), "mixed");
22393
22394 assert_eq!(infer_dtype(&[], true), "empty");
22395 }
22396
22397 #[test]
22398 fn test_na_nat_sentinels_and_eng_float_format() {
22399 use super::{
22400 NA, NAT, NaT, eng_float_format, get_eng_float_format, reset_eng_float_format,
22401 set_eng_float_format,
22402 };
22403
22404 assert!(NA.is_null());
22406 assert!(NAT.is_null());
22407 assert_eq!(NAT, NaT);
22408 assert_eq!(format!("{NA}"), "None");
22409 assert_eq!(format!("{NAT}"), "NaT");
22410
22411 assert_eq!(eng_float_format(1000.0, Some(3), false), "1.000E+03");
22413 assert_eq!(eng_float_format(0.005, Some(3), false), "5.000E-03");
22414 assert_eq!(eng_float_format(1234567.0, Some(3), false), "1.235E+06");
22415 assert_eq!(eng_float_format(-9876.54, Some(3), false), "-9.877E+03");
22416 assert_eq!(eng_float_format(0.0, Some(3), false), "0.000E+00");
22417
22418 assert_eq!(eng_float_format(1000.0, Some(3), true), "1.000k");
22420 assert_eq!(eng_float_format(0.005, Some(3), true), "5.000m");
22421 assert_eq!(eng_float_format(1234567.0, Some(3), true), "1.235M");
22422 assert_eq!(eng_float_format(-9876.54, Some(3), true), "-9.877k");
22423 assert_eq!(eng_float_format(0.0, Some(3), true), "0.000");
22424 assert_eq!(eng_float_format(1.5, Some(3), true), "1.500");
22425
22426 assert_eq!(eng_float_format(f64::NAN, Some(3), true), "NaN");
22428 assert_eq!(eng_float_format(f64::INFINITY, Some(3), true), "inf");
22429 assert_eq!(eng_float_format(f64::NEG_INFINITY, Some(3), true), "-inf");
22430
22431 reset_eng_float_format();
22433 assert_eq!(get_eng_float_format(), None);
22434 set_eng_float_format(4, true);
22435 assert_eq!(get_eng_float_format(), Some((4, true)));
22436 reset_eng_float_format();
22437 assert_eq!(get_eng_float_format(), None);
22438 }
22439
22440 #[test]
22441 fn test_options_system() {
22442 use super::{
22443 OptionError, OptionValue, describe_option, get_option, option_context, reset_option,
22444 set_option,
22445 };
22446
22447 reset_option(None).unwrap();
22449
22450 let max_rows = get_option("display.max_rows").unwrap();
22452 assert_eq!(max_rows.as_int(), Some(60));
22453 assert_eq!(max_rows, OptionValue::Int(60));
22454 assert!(!max_rows.is_none());
22455
22456 let min_rows = get_option("min_rows").unwrap();
22458 assert_eq!(min_rows.as_int(), Some(10));
22459
22460 set_option("display.max_rows", 100).unwrap();
22462 assert_eq!(get_option("display.max_rows").unwrap().as_int(), Some(100));
22463
22464 set_option("mode.sim_interactive", true).unwrap();
22465 assert_eq!(
22466 get_option("mode.sim_interactive").unwrap().as_bool(),
22467 Some(true)
22468 );
22469
22470 set_option("mode.chained_assignment", "raise").unwrap();
22471 assert_eq!(
22472 get_option("mode.chained_assignment").unwrap().as_str(),
22473 Some("raise")
22474 );
22475
22476 assert!(matches!(
22478 get_option("nonexistent.option"),
22479 Err(OptionError::NotFound { .. })
22480 ));
22481 assert!(matches!(
22482 get_option("display"),
22483 Err(OptionError::Ambiguous { .. })
22484 ));
22485
22486 let desc = describe_option(Some("max_rows")).unwrap();
22488 assert!(desc.contains("display.max_rows : [currently: 100]"));
22489
22490 let desc_all = describe_option(None).unwrap();
22491 assert!(desc_all.contains("display.width"));
22492 assert!(desc_all.contains("compute.use_bottleneck"));
22493
22494 {
22496 let _guard = option_context(&[
22497 ("display.max_rows", OptionValue::Int(999)),
22498 ("display.precision", OptionValue::Int(2)),
22499 ])
22500 .unwrap();
22501
22502 assert_eq!(get_option("display.max_rows").unwrap().as_int(), Some(999));
22503 assert_eq!(get_option("display.precision").unwrap().as_int(), Some(2));
22504 }
22505 assert_eq!(get_option("display.max_rows").unwrap().as_int(), Some(100));
22507 assert_eq!(get_option("display.precision").unwrap().as_int(), Some(6));
22508
22509 reset_option(Some("display.max_rows")).unwrap();
22511 assert_eq!(get_option("display.max_rows").unwrap().as_int(), Some(60));
22512
22513 reset_option(Some("all")).unwrap();
22514 assert_eq!(
22515 get_option("mode.chained_assignment").unwrap().as_str(),
22516 Some("warn")
22517 );
22518
22519 assert_eq!(
22521 get_option("mode.copy_on_write").unwrap().as_bool(),
22522 Some(false)
22523 );
22524 assert_eq!(
22525 get_option("mode.data_manager").unwrap().as_str(),
22526 Some("block")
22527 );
22528 assert_eq!(
22529 get_option("display.large_repr").unwrap().as_str(),
22530 Some("truncate")
22531 );
22532 assert_eq!(
22533 get_option("display.max_info_columns").unwrap().as_int(),
22534 Some(100)
22535 );
22536 assert_eq!(
22537 get_option("display.memory_usage").unwrap().as_bool(),
22538 Some(true)
22539 );
22540 assert_eq!(
22541 get_option("display.colheader_justify").unwrap().as_str(),
22542 Some("right")
22543 );
22544 assert!(get_option("display.chop_threshold").unwrap().is_none());
22545 assert_eq!(
22546 get_option("io.parquet.engine").unwrap().as_str(),
22547 Some("auto")
22548 );
22549 assert_eq!(
22550 get_option("plotting.backend").unwrap().as_str(),
22551 Some("matplotlib")
22552 );
22553 assert_eq!(
22554 get_option("plotting.matplotlib.register_converters")
22555 .unwrap()
22556 .as_bool(),
22557 Some(true)
22558 );
22559
22560 set_option("display.chop_threshold", ()).unwrap();
22562 assert!(get_option("display.chop_threshold").unwrap().is_none());
22563 }
22564
22565 #[test]
22566 fn test_scalar_typed_accessors() {
22567 use super::{Interval, IntervalClosed, Period, PeriodFreq, Scalar};
22568
22569 let s_i64 = Scalar::Int64(42);
22570 assert_eq!(s_i64.as_i64(), Some(42));
22571 assert_eq!(s_i64.as_int(), Some(42));
22572 assert_eq!(s_i64.as_f64(), None);
22573 assert_eq!(s_i64.as_float(), None);
22574 assert_eq!(s_i64.as_bool(), None);
22575 assert_eq!(s_i64.as_str(), None);
22576
22577 let s_f64 = Scalar::Float64(2.75);
22578 assert_eq!(s_f64.as_f64(), Some(2.75));
22579 assert_eq!(s_f64.as_float(), Some(2.75));
22580 assert_eq!(s_f64.as_i64(), None);
22581 assert_eq!(s_f64.as_int(), None);
22582
22583 let s_bool = Scalar::Bool(true);
22584 assert_eq!(s_bool.as_bool(), Some(true));
22585 assert_eq!(s_bool.as_int(), None);
22586
22587 let s_str = Scalar::Utf8("pandas".to_string());
22588 assert_eq!(s_str.as_str(), Some("pandas"));
22589 assert_eq!(s_str.as_bool(), None);
22590
22591 let s_dt = Scalar::Datetime64(1_000_000_000);
22592 assert_eq!(s_dt.as_datetime_nanos(), Some(1_000_000_000));
22593 assert_eq!(s_dt.as_str(), None);
22594
22595 let s_td = Scalar::Timedelta64(500_000);
22596 assert_eq!(s_td.as_timedelta_nanos(), Some(500_000));
22597 assert_eq!(s_td.as_int(), None);
22598
22599 let s_per = Scalar::Period(Period::new(2024, PeriodFreq::Daily));
22600 assert_eq!(s_per.as_period_ordinal(), Some(2024));
22601
22602 let s_iv = Scalar::Interval(Interval::new(0.0, 10.0, IntervalClosed::Both));
22603 assert_eq!(
22604 s_iv.as_interval(),
22605 Some(Interval::new(0.0, 10.0, IntervalClosed::Both))
22606 );
22607 }
22608
22609 #[test]
22610 fn test_api_submodules_and_types_inspectors() {
22611 use super::{
22612 DType, Scalar,
22613 api::{extensions, indexers, types},
22614 };
22615
22616 assert!(types::is_number(&Scalar::Int64(42)));
22618 assert!(types::is_number(&Scalar::Float64(42.5)));
22619 assert!(types::is_number(&Scalar::Bool(true)));
22620 assert!(!types::is_number(&Scalar::Utf8("pandas".into())));
22621
22622 assert!(types::is_bool(&Scalar::Bool(false)));
22623 assert!(!types::is_bool(&Scalar::Int64(0)));
22624
22625 assert!(types::is_integer(&Scalar::Int64(10)));
22626 assert!(!types::is_integer(&Scalar::Float64(10.0)));
22627
22628 assert!(types::is_float(&Scalar::Float64(10.0)));
22629 assert!(!types::is_float(&Scalar::Int64(10)));
22630
22631 assert!(types::is_float64_dtype(&DType::Float64));
22633 assert!(types::is_float64_dtype(&DType::Float64Nullable));
22634 assert!(!types::is_float64_dtype(&DType::Int64));
22635 assert!(!types::is_int32_dtype(&DType::Int64));
22636
22637 extensions::register_dataframe_accessor("geo");
22639 extensions::register_series_accessor("geo");
22640 extensions::register_index_accessor("geo");
22641
22642 let base = indexers::BaseIndexer::new(5, 1);
22644 assert_eq!(base.window_size, 5);
22645 assert_eq!(base.step, 1);
22646
22647 let fwd = indexers::FixedForwardWindowIndexer::new(3);
22648 assert_eq!(fwd.window_size, 3);
22649
22650 let var = indexers::VariableOffsetWindowIndexer::new(100);
22651 assert_eq!(var.index_offset, 100);
22652 }
22653
22654 #[test]
22655 fn test_extension_dtypes_and_parameterized_parsing() {
22656 use super::{
22657 AsDType, CategoricalDtype, DType, IntervalClosed, IntervalDtype, PeriodDtype, Scalar,
22658 SparseDType, api::types, pandas_dtype,
22659 };
22660
22661 let cat_default = CategoricalDtype::default();
22663 assert_eq!(cat_default.name(), "category");
22664 assert_eq!(cat_default.kind(), "O");
22665 assert!(!cat_default.ordered());
22666 assert_eq!(cat_default.categories(), None);
22667 assert_eq!(cat_default.as_dtype(), DType::Categorical);
22668 assert!(types::is_categorical_dtype(&cat_default));
22669 assert_eq!(
22670 cat_default.to_string(),
22671 "CategoricalDtype(categories=None, ordered=False)"
22672 );
22673
22674 let cat_custom =
22675 CategoricalDtype::new(Some(vec!["low".to_string(), "high".to_string()]), true);
22676 assert!(cat_custom.ordered());
22677 assert_eq!(
22678 cat_custom.categories(),
22679 Some(&["low".to_string(), "high".to_string()][..])
22680 );
22681 assert!(cat_custom.to_string().contains("ordered=True"));
22682
22683 let per_default = PeriodDtype::default();
22685 assert_eq!(per_default.freq(), "D");
22686 assert_eq!(per_default.name(), "period[D]");
22687 assert_eq!(per_default.kind(), "O");
22688 assert_eq!(per_default.as_dtype(), DType::Period);
22689 assert!(types::is_period_dtype(&per_default));
22690 assert_eq!(per_default.to_string(), "period[D]");
22691
22692 let per_custom = PeriodDtype::new("M");
22693 assert_eq!(per_custom.freq(), "M");
22694 assert_eq!(per_custom.to_string(), "period[M]");
22695
22696 let int_default = IntervalDtype::default();
22698 assert_eq!(*int_default.subtype(), DType::Float64);
22699 assert_eq!(int_default.closed(), Some(IntervalClosed::Right));
22700 assert_eq!(int_default.name(), "interval");
22701 assert_eq!(int_default.kind(), "O");
22702 assert_eq!(int_default.as_dtype(), DType::Interval);
22703 assert!(types::is_interval_dtype(&int_default));
22704 assert_eq!(int_default.to_string(), "interval[float64, right]");
22705
22706 let int_custom = IntervalDtype::new(DType::Int64, Some(IntervalClosed::Both));
22707 assert_eq!(*int_custom.subtype(), DType::Int64);
22708 assert_eq!(int_custom.closed(), Some(IntervalClosed::Both));
22709 assert_eq!(int_custom.to_string(), "interval[int64, both]");
22710
22711 let sp = SparseDType::new(DType::Float64, Scalar::Float64(0.0)).unwrap();
22713 assert_eq!(sp.as_dtype(), DType::Sparse);
22714 assert!(types::is_sparse(&sp));
22715
22716 assert_eq!(pandas_dtype("period[D]").unwrap(), DType::Period);
22718 assert_eq!(pandas_dtype("Period[M]").unwrap(), DType::Period);
22719 assert_eq!(pandas_dtype("interval[float64]").unwrap(), DType::Interval);
22720 assert_eq!(pandas_dtype("Interval[int64]").unwrap(), DType::Interval);
22721 assert_eq!(pandas_dtype("sparse[float64]").unwrap(), DType::Sparse);
22722 assert_eq!(pandas_dtype("Sparse[int64, 0]").unwrap(), DType::Sparse);
22723 }
22724}
22725
22726#[cfg(test)]
22729mod numeric_width_fvsao23 {
22730 use super::{DType, NumericWidth, NumpyNumeric, numpy_pairwise_sum};
22731
22732 #[test]
22733 fn float32_sum_is_numpys_pairwise_sum_bit_for_bit() {
22734 let cases: [(usize, u32); 5] = [
22738 (5, 1_083_829_126),
22739 (64, 1_136_679_190),
22740 (129, 1_145_981_108),
22741 (1000, 1_170_926_592),
22742 (4097, 1_188_011_795),
22743 ];
22744 for (n, bits) in cases {
22745 #[allow(clippy::cast_precision_loss)] let values: Vec<f32> = (0..n)
22747 .map(|k| ((k * 37) % 1000) as f32 * 0.013_f32)
22748 .collect();
22749 assert_eq!(numpy_pairwise_sum(&values).to_bits(), bits, "n={n}");
22750 if n < 100 {
22751 #[allow(clippy::cast_possible_truncation)]
22752 let rounded_once = values.iter().map(|&v| f64::from(v)).sum::<f64>() as f32;
22753 assert_ne!(rounded_once.to_bits(), bits, "n={n}");
22754 }
22755 }
22756 assert_eq!(numpy_pairwise_sum::<f32>(&[]), 0.0);
22757 }
22758
22759 #[test]
22760 fn names_parse_and_round_trip() {
22761 for width in NumericWidth::ALL {
22762 for nullable in [false, true] {
22763 assert_eq!(
22764 NumericWidth::parse(width.name(nullable)),
22765 Some((width, nullable))
22766 );
22767 }
22768 }
22769 for (name, expected) in [
22770 ("<i4", (NumericWidth::Int32, false)),
22771 ("f4", (NumericWidth::Float32, false)),
22772 ("UInt8Dtype", (NumericWidth::UInt8, true)),
22773 ] {
22774 assert_eq!(NumericWidth::parse(name), Some(expected), "{name}");
22775 }
22776 for name in ["int64", "Int64", "float64", "i8", "f8", "int", "float"] {
22778 assert_eq!(NumericWidth::parse(name), None, "{name}");
22779 }
22780 }
22781
22782 #[test]
22783 fn wrapping_is_numpys_modular_cast_not_saturation() {
22784 assert_eq!(NumericWidth::Int8.wrap_int(300), Some(44));
22786 assert_eq!(NumericWidth::UInt8.wrap_int(-5), Some(251));
22788 assert_eq!(NumericWidth::UInt16.wrap_int(-5), Some(65531));
22789 assert_eq!(NumericWidth::UInt32.wrap_int(-5), Some(4_294_967_291));
22790 assert_eq!(NumericWidth::Int8.wrap_int(200), Some(-56));
22792 assert_eq!(
22793 NumericWidth::Int32.wrap_int(i64::from(i32::MAX) + 1),
22794 Some(i64::from(i32::MIN))
22795 );
22796 let product = 50_000_i64.wrapping_pow(5);
22798 assert_eq!(
22799 NumericWidth::Int32.wrap_int(product),
22800 Some(i64::from(50_000_i32.wrapping_pow(5)))
22801 );
22802 assert_eq!(NumericWidth::UInt64.wrap_int(-1), None);
22804 assert_eq!(NumericWidth::UInt64.wrap_int(7), Some(7));
22805 assert_eq!(NumericWidth::Float32.wrap_int(1), None);
22806 assert!(NumericWidth::Int8.holds_int(-128) && !NumericWidth::Int8.holds_int(128));
22807 }
22808
22809 #[test]
22810 fn float32_rounding_is_to_nearest_not_truncation() {
22811 assert_eq!(NumericWidth::round_f32(0.1), 0.100_000_001_490_116_12);
22813 let sum =
22816 NumericWidth::round_f32(NumericWidth::round_f32(0.1) + NumericWidth::round_f32(0.2));
22817 assert_eq!(sum, 0.300_000_011_920_928_96);
22818 assert_eq!(NumericWidth::round_f32(1.0 + 2f64.powi(-24)), 1.0);
22821 let above_tie = 1.0 + 3.0 * 2f64.powi(-25);
22822 assert_eq!(NumericWidth::round_f32(above_tie), 1.0 + 2f64.powi(-23));
22823 assert!(NumericWidth::round_f32(f64::NAN).is_nan());
22824 assert_eq!(NumericWidth::round_f32(1e300), f64::INFINITY);
22825 }
22826
22827 #[test]
22828 fn result_type_matches_numpy_promotion() {
22829 use NumpyNumeric::{Bool, Float, Int, UInt};
22830 let cases = [
22831 (Int(32), Int(64), Int(64)), (Int(8), UInt(8), Int(16)), (Int(16), UInt(8), Int(16)),
22834 (Int(8), UInt(16), Int(32)),
22835 (Int(32), UInt(32), Int(64)),
22836 (Int(64), UInt(64), Float(64)), (UInt(8), UInt(32), UInt(32)),
22838 (Float(32), Int(8), Float(32)), (Float(32), UInt(16), Float(32)),
22840 (Float(32), Int(32), Float(64)), (Float(32), Float(64), Float(64)),
22842 (Bool, Int(8), Int(8)),
22843 (Bool, Float(32), Float(32)),
22844 ];
22845 for (a, b, expected) in cases {
22846 assert_eq!(a.result_type(b), expected, "{a:?} {b:?}");
22847 assert_eq!(b.result_type(a), expected, "{b:?} {a:?}");
22848 }
22849 assert_eq!(Int(32).with_python_int(), Int(32));
22852 assert_eq!(Int(32).with_python_float(), Float(64));
22853 assert_eq!(Float(32).with_python_float(), Float(32));
22854 assert_eq!(Bool.with_python_int(), Int(64));
22855 }
22856
22857 #[test]
22858 fn columns_map_to_numpy_dtypes() {
22859 let cases = [
22860 (DType::Int64, None, Some(NumpyNumeric::Int(64))),
22861 (
22862 DType::Int64Nullable,
22863 Some(NumericWidth::UInt8),
22864 Some(NumpyNumeric::UInt(8)),
22865 ),
22866 (
22867 DType::Float64,
22868 Some(NumericWidth::Float32),
22869 Some(NumpyNumeric::Float(32)),
22870 ),
22871 (DType::Float64, Some(NumericWidth::Int8), None),
22873 (DType::Utf8, None, None),
22874 ];
22875 for (dtype, width, expected) in cases {
22876 assert_eq!(NumpyNumeric::of(&dtype, width), expected, "{dtype:?}");
22877 }
22878 for width in NumericWidth::ALL {
22879 assert_eq!(NumpyNumeric::of_width(width).width(), Some(width));
22880 assert!(width.fits_storage(&width.storage(false)));
22881 assert!(width.fits_storage(&width.storage(true)));
22882 }
22883 assert_eq!(NumpyNumeric::Int(64).width(), None);
22884 }
22885
22886 #[test]
22887 fn downcast_and_category_code_widths() {
22888 let int32_max_plus_one = i64::from(i32::MAX) + 1;
22891 let signed = [
22892 ((1, 2), Some(NumericWidth::Int8)),
22893 ((1, 300), Some(NumericWidth::Int16)),
22894 ((0, int32_max_plus_one), None),
22895 ];
22896 for ((low, high), expected) in signed {
22897 assert_eq!(NumericWidth::smallest_signed(low, high), expected);
22898 }
22899 let unsigned = [((1, 300), Some(NumericWidth::UInt16)), ((-1, 3), None)];
22900 for ((low, high), expected) in unsigned {
22901 assert_eq!(NumericWidth::smallest_unsigned(low, high), expected);
22902 }
22903 for (categories, expected) in [
22905 (2, NumericWidth::Int8),
22906 (126, NumericWidth::Int8),
22907 (127, NumericWidth::Int16),
22908 (200, NumericWidth::Int16),
22909 ] {
22910 assert_eq!(NumericWidth::for_category_codes(categories), Some(expected));
22911 }
22912 assert_eq!(NumericWidth::itemsize(NumericWidth::Int8), 1);
22913 assert_eq!(NumericWidth::Float32.itemsize(), 4);
22914 }
22915}
22916
22917#[cfg(test)]
22922mod pandas_reductions_9iim6 {
22923 use super::{MissingLayout, PandasReductions, ReductionValues};
22924
22925 #[allow(clippy::cast_precision_loss)] fn floats(n: usize) -> (Vec<f64>, Vec<u64>) {
22929 let mut present = vec![0_u64; n.div_ceil(64)];
22930 let values = (0..n)
22931 .map(|k| {
22932 if k % 11 != 3 {
22933 present[k / 64] |= 1 << (k % 64);
22934 }
22935 let base = ((k * 7919 + 13) % 100_003) as f64 / 7.0 - 7000.0;
22936 if k % 5 == 0 { base * 1e6 } else { base }
22937 })
22938 .collect();
22939 (values, present)
22940 }
22941
22942 fn ints(n: usize) -> Vec<i64> {
22944 (0..n)
22945 .map(|k| i64::try_from((k * 7919 + 13) % 100_003).unwrap() * 3_000_000_007)
22946 .collect()
22947 }
22948
22949 fn assert_bits(got: &[f64], expected: &[u64], case: &str) {
22950 let got: Vec<u64> = got.iter().map(|value| value.to_bits()).collect();
22951 assert_eq!(got, expected, "{case}");
22952 }
22953
22954 #[test]
22955 fn numpy_float64_with_nan_matches_pandas_bits() {
22956 let cases: [(usize, [u64; 7]); 7] = [
22958 (
22959 7,
22960 [
22961 0xc1ff_1185_2dcb_6db6,
22962 0xc1d4_b658_c932_4924,
22963 0x43db_301d_4a8d_87a3,
22964 0x41e4_db58_e2f1_458e,
22965 0x41d1_078f_09d3_9c5c,
22966 0xc002_1f47_ceae_1b43,
22967 0x4014_c8bc_93df_56e6,
22968 ],
22969 ),
22970 (
22971 8,
22972 [
22973 0xc1ff_1184_f43d_b6da,
22974 0xc1d1_c0de_426c_687d,
22975 0x43d7_9d3c_ecd2_da2b,
22976 0x41e3_7012_7d6c_71a5,
22977 0x41cd_631d_3379_9929,
22978 0xc003_b196_82f9_28dc,
22979 0x4018_9de2_eba9_5ecc,
22980 ],
22981 ),
22982 (
22983 127,
22984 [
22985 0x4200_324e_3389_2490,
22986 0x4192_0704_ad1e_360d,
22987 0x43c9_4a6b_3390_577d,
22988 0x41dc_72bf_d6fa_9808,
22989 0x41a5_38f5_8417_ae1e,
22990 0x3fd0_b6bf_045c_e4d5,
22991 0x4017_1585_bf13_21c4,
22992 ],
22993 ),
22994 (
22995 128,
22996 [
22997 0x4200_324d_7236_db6e,
22998 0x4191_df3a_f99d_a2ae,
22999 0x43c9_1234_ffb7_4a93,
23000 0x41dc_5310_c97c_292c,
23001 0x41a5_09f4_cfcf_9206,
23002 0x3fd0_d9df_0d68_00b0,
23003 0x4017_61b6_5653_ae82,
23004 ],
23005 ),
23006 (
23007 129,
23008 [
23009 0x4200_324c_d43e_db71,
23010 0x4191_b81f_8a1d_61da,
23011 0x43c8_daf6_85d3_386f,
23012 0x41dc_33ca_af49_8c24,
23013 0x41a4_dbc2_8609_a567,
23014 0x3fd0_fcc5_39d9_6901,
23015 0x4017_ade4_7855_7c25,
23016 ],
23017 ),
23018 (
23019 1000,
23020 [
23021 0x421a_d4f6_8061_248e,
23022 0x417e_39f9_3e1a_a248,
23023 0x43c7_9481_cba1_263b,
23024 0x41db_7825_28c0_37cc,
23025 0x418d_27ba_a0ea_2f9a,
23026 0x3fc8_e53a_e277_3d7f,
23027 0x4018_3c97_3603_dfd0,
23028 ],
23029 ),
23030 (
23031 100_000,
23032 [
23033 0x4283_088c_316e_46dc,
23034 0x417b_7135_0c27_1185,
23035 0x43c7_a0de_3b8e_ea34,
23036 0x41db_7f57_6673_8d6b,
23037 0x4157_58cc_33fd_4ae6,
23038 0x3fc7_f1cf_b14a_14c8,
23039 0x4018_06b5_f26a_c384,
23040 ],
23041 ),
23042 ];
23043 let all = |r: &PandasReductions<'_>| {
23044 [
23045 r.sum(),
23046 r.mean(),
23047 r.var(1),
23048 r.std(1),
23049 r.sem(1),
23050 r.skew(),
23051 r.kurt(),
23052 ]
23053 };
23054 for (n, expected) in cases {
23055 let (values, present) = floats(n);
23056 let r = PandasReductions::new(
23057 ReductionValues::Float(&values),
23058 Some(&present),
23059 MissingLayout::Numpy,
23060 );
23061 assert_bits(&all(&r), &expected, &format!("float64 n={n}"));
23062 let with_nan: Vec<f64> = values
23065 .iter()
23066 .enumerate()
23067 .map(|(k, &value)| if k % 11 == 3 { f64::NAN } else { value })
23068 .collect();
23069 let r = PandasReductions::numpy_nan_missing(ReductionValues::Float(&with_nan));
23070 assert_bits(&all(&r), &expected, &format!("float64 NaN n={n}"));
23071 let (head, tail) = with_nan.split_at(n / 3);
23072 let chunks = [head, tail];
23073 let r = PandasReductions::numpy_nan_missing(ReductionValues::FloatChunks(&chunks));
23074 assert_bits(&all(&r), &expected, &format!("float64 NaN chunks n={n}"));
23075 }
23076 let (values, present) = floats(100_000);
23078 let left_fold: f64 = values
23079 .iter()
23080 .enumerate()
23081 .filter(|&(k, _)| present[k / 64] >> (k % 64) & 1 == 1)
23082 .map(|(_, value)| value)
23083 .sum();
23084 assert_ne!(left_fold.to_bits(), 0x4283_088c_316e_46dc);
23085 }
23086
23087 #[test]
23088 fn numpy_int64_mean_sums_through_the_cast_buffer() {
23089 let cases: [(usize, [u64; 5]); 3] = [
23091 (
23092 129,
23093 [
23094 0x42e0_dda2_9987_3f9e,
23095 0x45b9_0e2a_887d_aeda,
23096 0x429c_34a1_c273_372f,
23097 0x3f95_9e9d_c69e_ec88,
23098 0xbff3_844b_ba13_eac1,
23099 ],
23100 ),
23101 (
23102 8193,
23103 [
23104 0x42e1_0d5b_e407_5aa7,
23105 0x45b8_3bf5_04f5_f2fc,
23106 0x426b_d893_c5c9_85b1,
23107 0x3f42_7452_ff15_86c7,
23108 0xbff3_318c_611b_b59c,
23109 ],
23110 ),
23111 (
23112 20_000,
23113 [
23114 0x42e1_0d17_ebf8_272d,
23115 0x45b8_3c24_c921_82b6,
23116 0x4261_d2a2_f139_68e2,
23117 0x3f31_a21c_d4bb_ff52,
23118 0xbff3_328c_4edc_26ee,
23119 ],
23120 ),
23121 ];
23122 for (n, expected) in cases {
23123 let values = ints(n);
23124 let r =
23125 PandasReductions::new(ReductionValues::Int(&values), None, MissingLayout::Numpy);
23126 let got = [r.mean(), r.var(1), r.sem(1), r.skew(), r.kurt()];
23127 assert_bits(&got, &expected, &format!("int64 n={n}"));
23128 let (head, tail) = values.split_at(n / 3);
23130 let (middle, rest) = tail.split_at(1);
23131 let chunks = [head, middle, &[][..], rest];
23132 let chunked = PandasReductions::new(
23133 ReductionValues::IntChunks(&chunks),
23134 None,
23135 MissingLayout::Numpy,
23136 );
23137 let got = [
23138 chunked.mean(),
23139 chunked.var(1),
23140 chunked.sem(1),
23141 chunked.skew(),
23142 chunked.kurt(),
23143 ];
23144 assert_bits(&got, &expected, &format!("int64 chunks n={n}"));
23145 }
23146 }
23147
23148 #[test]
23149 fn masked_columns_add_runs_of_present_values() {
23150 let cases: [(usize, [u64; 4]); 3] = [
23154 (
23155 129,
23156 [
23157 0x4200_324c_d43e_db6e,
23158 0x4191_b81f_8a1d_61d6,
23159 0x43c8_daf6_85d3_3872,
23160 0x41a4_dbc2_8609_a567,
23161 ],
23162 ),
23163 (
23164 1000,
23165 [
23166 0x421a_d4f6_8061_2492,
23167 0x417e_39f9_3e1a_a24c,
23168 0x43c7_9481_cba1_263a,
23169 0x418d_27ba_a0ea_2f9a,
23170 ],
23171 ),
23172 (
23173 100_000,
23174 [
23175 0x4283_088c_316e_46de,
23176 0x417b_7135_0c27_1188,
23177 0x43c7_a0de_3b8e_ea37,
23178 0x4157_58cc_33fd_4ae6,
23179 ],
23180 ),
23181 ];
23182 for (n, expected) in cases {
23183 let (values, present) = floats(n);
23184 let r = PandasReductions::new(
23185 ReductionValues::Float(&values),
23186 Some(&present),
23187 MissingLayout::Masked,
23188 );
23189 assert_bits(
23190 &[r.sum(), r.mean(), r.var(1), r.sem(1)],
23191 &expected,
23192 &format!("Float64 n={n}"),
23193 );
23194 let (head, tail) = values.split_at(n / 2 + 1);
23195 let chunks = [head, tail];
23196 let chunked = PandasReductions::new(
23197 ReductionValues::FloatChunks(&chunks),
23198 Some(&present),
23199 MissingLayout::Masked,
23200 );
23201 let got = [
23202 chunked.sum(),
23203 chunked.mean(),
23204 chunked.var(1),
23205 chunked.sem(1),
23206 ];
23207 assert_bits(&got, &expected, &format!("Float64 chunks n={n}"));
23208 }
23209 for (n, expected) in [
23212 (8193, [0x42e1_0f35_29c2_807b_u64, 0x45b8_39ed_8746_bdcc]),
23213 (20_000, [0x42e1_0cf2_cc56_752a, 0x45b8_3c63_72fc_fad5]),
23214 ] {
23215 let values = ints(n);
23216 let mut present = vec![0_u64; n.div_ceil(64)];
23217 for k in (0..n).filter(|k| k % 997 != 5) {
23218 present[k / 64] |= 1 << (k % 64);
23219 }
23220 let r = PandasReductions::new(
23221 ReductionValues::Int(&values),
23222 Some(&present),
23223 MissingLayout::Masked,
23224 );
23225 assert_bits(&[r.mean(), r.var(1)], &expected, &format!("Int64 n={n}"));
23226 }
23227 }
23228
23229 #[test]
23230 fn edge_cases_match_pandas() {
23231 let reductions = |values: &[f64], present: Option<&[u64]>| {
23232 let r = PandasReductions::new(
23233 ReductionValues::Float(values),
23234 present,
23235 MissingLayout::Numpy,
23236 );
23237 [r.sum(), r.mean(), r.var(1), r.sem(1), r.skew(), r.kurt()]
23238 };
23239 let constant = reductions(&[1.5; 10], None);
23242 assert_eq!(constant, [15.0, 1.5, 0.0, 0.0, 0.0, 0.0]);
23243 assert!(reductions(&[2.0; 3], None)[5].is_nan());
23244 assert!(reductions(&[1.0, 2.0], None)[4].is_nan());
23246 assert_eq!(
23247 reductions(&[1.0, 2.0, 4.0], None)[4],
23248 0.935_219_529_582_823_7
23249 );
23250 let empty = reductions(&[], None);
23252 assert_eq!(empty[0], 0.0);
23253 assert!(empty[1..].iter().all(|value| value.is_nan()));
23254 let all_missing = reductions(&[3.0; 5], Some(&[0]));
23255 assert_eq!(all_missing[0], 0.0);
23256 assert!(all_missing[1].is_nan());
23257 assert_eq!(
23259 reductions(&[-0.0; 10], None)[0].to_bits(),
23260 0.0_f64.to_bits()
23261 );
23262 let inf = reductions(&[1.0, f64::INFINITY, 2.0, 5.0], None);
23264 assert_eq!(inf[0], f64::INFINITY);
23265 assert!(inf[2..].iter().all(|value| value.is_nan()));
23266 }
23267
23268 #[test]
23269 fn int64_mean_skipping_is_the_filled_mean_vk7y9() {
23270 const NAT: i64 = i64::MIN;
23274 let nanos: Vec<i64> = (0..20_000_i64)
23275 .map(|k| {
23276 if k % 13 == 5 {
23277 NAT
23278 } else {
23279 1_577_836_800_000_000_000 + k * 3_600_000_000_123
23280 }
23281 })
23282 .collect();
23283 let mut present = vec![0_u64; nanos.len().div_ceil(64)];
23284 let filled: Vec<i64> = nanos
23285 .iter()
23286 .enumerate()
23287 .map(|(i, &ns)| {
23288 if ns == NAT {
23289 0
23290 } else {
23291 present[i / 64] |= 1 << (i % 64);
23292 ns
23293 }
23294 })
23295 .collect();
23296 let expected = PandasReductions::new(
23297 ReductionValues::Int(&filled),
23298 Some(&present),
23299 MissingLayout::Numpy,
23300 )
23301 .mean();
23302 assert_eq!(
23303 PandasReductions::int64_mean_skipping(&nanos, NAT).to_bits(),
23304 expected.to_bits()
23305 );
23306 assert!(PandasReductions::int64_mean_skipping(&[NAT, NAT], NAT).is_nan());
23308 assert!(PandasReductions::int64_mean_skipping(&[], NAT).is_nan());
23309 }
23310}
23311
23312#[cfg(test)]
23316mod pandas_decimal_py3c0 {
23317 use super::{PandasDecimal, pandas_decimal_to_f64, pandas_int_to_f64};
23318
23319 fn bits(token: &str) -> u64 {
23320 match pandas_decimal_to_f64(token.as_bytes()) {
23321 PandasDecimal::Value(value) => value.to_bits(),
23322 other => panic!("{token:?}: {other:?}"),
23323 }
23324 }
23325
23326 #[test]
23327 fn tokens_convert_to_pandas_bits() {
23328 let cases = [
23329 ("9.890295358649789", 0x4023_c7d4_cb12_5ce4),
23330 ("0.8690736625851781286570704999", 0x3feb_cf73_91d3_c8f1),
23331 ("0.000000068288360759838675650889", 0x3e72_54bd_8bcd_610b),
23332 ("-0.0080749473608410608782560", 0xbf80_8999_16a7_63f3),
23333 ("99999999999999999", 0x4376_3457_85d8_a001),
23334 ("1234567890123456789012345", 0x44f0_56e0_f36a_6444),
23335 ("00000000000000000.5", 0x0000_0000_0000_0000),
23337 ("-00000000000000000.5", 0x8000_0000_0000_0000),
23338 ("1.5E+10", 0x420b_f08e_b000_0000),
23339 ("-.5e-3", 0xbf40_624d_d2f1_a9fc),
23340 ("5.", 0x4014_0000_0000_0000),
23341 ("1e-320", 0x0000_0000_0000_07e8),
23342 ("2.5e-310", 0x0000_2e05_5c9a_3f6c),
23343 ("-1e-400", 0x8000_0000_0000_0000),
23344 ("-1e-700", 0x0000_0000_0000_0000),
23346 ("1e-4294967296", 0x3ff0_0000_0000_0000),
23348 ("1.7976931348623157e308", 0x7fef_ffff_ffff_ffff),
23349 ("0.001e310", 0x7fac_7b1f_3cac_7433),
23350 ];
23351 for (token, expected) in cases {
23352 assert_eq!(bits(token), expected, "{token:?}");
23353 }
23354 let correctly_rounded: f64 = "9.890295358649789".parse().unwrap();
23356 assert_ne!(correctly_rounded.to_bits(), 0x4023_c7d4_cb12_5ce4);
23357 }
23358
23359 #[test]
23360 fn what_pandas_does_not_read_as_a_float() {
23361 for token in [
23362 "1e309",
23363 "0e400",
23364 "1.8e308",
23365 "1e+0000000000000000001",
23366 "1e-2147483649",
23367 "1e",
23368 "1e+",
23369 "1.5d3",
23370 "0x10",
23371 "1_000.5",
23372 "1..5",
23373 ] {
23374 assert_eq!(
23375 pandas_decimal_to_f64(token.as_bytes()),
23376 PandasDecimal::Rejected,
23377 "{token:?}"
23378 );
23379 }
23380 for token in ["inf", "-Infinity", "nan", ".", "-", "e5", "+.e1", "--1", ""] {
23381 assert_eq!(
23382 pandas_decimal_to_f64(token.as_bytes()),
23383 PandasDecimal::NotDecimal,
23384 "{token:?}"
23385 );
23386 }
23387 }
23388
23389 #[test]
23390 fn an_integer_in_a_float_column_takes_the_same_conversion() {
23391 assert_eq!(pandas_int_to_f64(-42).to_bits(), (-42.0_f64).to_bits());
23392 assert_eq!(
23393 pandas_int_to_f64(99_999_999_999_999_999).to_bits(),
23394 0x4376_3457_85d8_a001
23395 );
23396 assert_eq!(
23397 pandas_int_to_f64(-99_999_999_999_999_999).to_bits(),
23398 0xc376_3457_85d8_a001
23399 );
23400 }
23401
23402 #[test]
23409 fn calendar_months_match_chrono_relativedelta_4g57c() {
23410 use chrono::{Datelike, NaiveDate};
23411
23412 use super::add_calendar_months_nanos;
23413 let reference = |nanos: i64, months: i64| -> Option<i64> {
23414 let at = chrono::DateTime::from_timestamp(
23415 nanos.div_euclid(1_000_000_000),
23416 u32::try_from(nanos.rem_euclid(1_000_000_000)).ok()?,
23417 )?
23418 .naive_utc();
23419 let total = i64::from(at.year())
23420 .checked_mul(12)?
23421 .checked_add(i64::from(at.month0()))?
23422 .checked_add(months)?;
23423 let year = i32::try_from(total.div_euclid(12)).ok()?;
23424 let month = u32::try_from(total.rem_euclid(12)).ok()? + 1;
23425 let last = (28..=31)
23426 .rev()
23427 .find(|day| NaiveDate::from_ymd_opt(year, month, *day).is_some())?;
23428 NaiveDate::from_ymd_opt(year, month, at.day().min(last))?
23429 .and_time(at.time())
23430 .and_utc()
23431 .timestamp_nanos_opt()
23432 };
23433 let day_nanos = 86_400_000_000_000_i64;
23434 let mut checked = 0;
23435 for year in [1678, 1699, 1900, 1969, 1970, 2000, 2023, 2024, 2100, 2261] {
23436 for month in 1..=12 {
23437 for day in [1, 15, 27, 28, 29, 30, 31] {
23438 let Some(date) = NaiveDate::from_ymd_opt(year, month, day) else {
23439 continue;
23440 };
23441 let Some(midnight) = date
23442 .and_hms_opt(0, 0, 0)
23443 .and_then(|at| at.and_utc().timestamp_nanos_opt())
23444 else {
23445 continue;
23446 };
23447 for time in [0, 1, 37_123_456_789, day_nanos - 1] {
23448 let nanos = midnight + time;
23449 for months in [-2400, -13, -12, -1, 0, 1, 2, 11, 12, 25, 1200] {
23450 assert_eq!(
23451 add_calendar_months_nanos(nanos, months),
23452 reference(nanos, months),
23453 "{nanos} + {months} months"
23454 );
23455 checked += 1;
23456 }
23457 }
23458 }
23459 }
23460 }
23461 assert!(checked > 30_000, "{checked}");
23462 let last = i64::MAX - 1;
23464 assert_eq!(add_calendar_months_nanos(last, 1), None);
23465 assert_eq!(reference(last, 1), None);
23466 assert_eq!(add_calendar_months_nanos(i64::MIN + 1, -1), None);
23467 assert_eq!(add_calendar_months_nanos(0, i64::MAX), None);
23468 assert_eq!(add_calendar_months_nanos(0, i64::MIN), None);
23469 assert_eq!(add_calendar_months_nanos(0, 12 * 400), None);
23470 assert_eq!(super::add_calendar_months_days(i64::MAX, 1), None);
23471 assert_eq!(super::add_calendar_months_days(0, i64::MAX), None);
23472 let jan31 = 19_753 * day_nanos;
23474 assert_eq!(
23475 add_calendar_months_nanos(jan31, 1),
23476 Some(19_782 * day_nanos)
23477 );
23478 }
23479
23480 #[test]
23486 fn numbered_host_values_compare_and_hash_by_number_jq8qb() {
23487 use std::hash::{Hash, Hasher};
23488
23489 use super::{HostObject, HostValue, ObjectValue};
23490
23491 struct Numbered(Option<i64>, &'static str);
23492 impl HostObject for Numbered {
23493 fn host_eq(&self, other: &dyn HostObject) -> bool {
23494 other
23495 .as_any()
23496 .downcast_ref::<Self>()
23497 .is_some_and(|other| other.1 == self.1)
23498 }
23499 fn host_repr(&self) -> String {
23500 self.1.to_owned()
23501 }
23502 fn host_str(&self) -> String {
23503 self.1.to_owned()
23504 }
23505 fn host_hash(&self) -> Option<u64> {
23506 Some(self.1.len() as u64)
23507 }
23508 fn host_cmp(&self, _other: &dyn HostObject) -> Option<std::cmp::Ordering> {
23509 None
23510 }
23511 fn as_any(&self) -> &dyn std::any::Any {
23512 self
23513 }
23514 fn host_number(&self) -> Option<i64> {
23515 self.0
23516 }
23517 }
23518 let hash = |value: &ObjectValue| {
23519 let mut hasher = std::hash::DefaultHasher::new();
23520 value.hash(&mut hasher);
23521 hasher.finish()
23522 };
23523 let cell = |number, name| ObjectValue::Host(HostValue::new(Numbered(number, name)));
23524 assert_eq!(cell(Some(7), "a"), cell(Some(7), "b"));
23525 assert_eq!(hash(&cell(Some(7), "a")), hash(&cell(Some(7), "bb")));
23526 assert_ne!(cell(Some(7), "a"), cell(Some(8), "a"));
23527 assert_eq!(cell(Some(7), "a"), cell(None, "a"));
23528 assert_ne!(cell(Some(7), "a"), cell(None, "b"));
23529 assert_eq!(cell(None, "a"), cell(None, "a"));
23530 assert_ne!(cell(None, "a"), cell(None, "b"));
23531 assert_eq!(hash(&cell(None, "ab")), hash(&cell(None, "cd")));
23532 }
23533}