Path: blob/main/crates/polars-ops/src/series/ops/eager.rs
8448 views
use polars_core::prelude::DataType;1use polars_core::series::Series;2use polars_error::PolarsResult;34pub trait ShrinkType {5fn shrink_type(&self) -> PolarsResult<Series>;6}78impl ShrinkType for Series {9fn shrink_type(&self) -> PolarsResult<Series> {10if !self.dtype().is_primitive_numeric() {11return Ok(self.clone());12}1314if self.dtype().is_float() {15return self.cast(&DataType::Float32);16}1718if self.dtype().is_unsigned_integer() {19let max = self.max_reduce()?.value().extract::<u128>().unwrap_or(0);2021if cfg!(feature = "dtype-u8") && max <= u8::MAX as u128 {22self.cast(&DataType::UInt8)23} else if cfg!(feature = "dtype-u16") && max <= u16::MAX as u128 {24self.cast(&DataType::UInt16)25} else if max <= u32::MAX as u128 {26self.cast(&DataType::UInt32)27} else if max <= u64::MAX as u128 {28self.cast(&DataType::UInt64)29} else {30Ok(self.clone())31}32} else {33let min = self.min_reduce()?.value().extract::<i128>().unwrap_or(0);34let max = self.max_reduce()?.value().extract::<i128>().unwrap_or(0);3536if cfg!(feature = "dtype-i8") && min >= i8::MIN as i128 && max <= i8::MAX as i128 {37self.cast(&DataType::Int8)38} else if cfg!(feature = "dtype-i16")39&& min >= i16::MIN as i12840&& max <= i16::MAX as i12841{42self.cast(&DataType::Int16)43} else if min >= i32::MIN as i128 && max <= i32::MAX as i128 {44self.cast(&DataType::Int32)45} else if min >= i64::MIN as i128 && max <= i64::MAX as i128 {46self.cast(&DataType::Int64)47} else {48Ok(self.clone())49}50}51}52}535455