Path: blob/main/crates/polars-ops/src/series/ops/eager.rs
6939 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::<u64>().unwrap_or(0_u64);2021if cfg!(feature = "dtype-u8") && max <= u8::MAX as u64 {22self.cast(&DataType::UInt8)23} else if cfg!(feature = "dtype-u16") && max <= u16::MAX as u64 {24self.cast(&DataType::UInt16)25} else if max <= u32::MAX as u64 {26self.cast(&DataType::UInt32)27} else {28Ok(self.clone())29}30} else {31let min = self.min_reduce()?.value().extract::<i64>().unwrap_or(0_i64);32let max = self.max_reduce()?.value().extract::<i64>().unwrap_or(0_i64);3334if cfg!(feature = "dtype-i8") && min >= i8::MIN as i64 && max <= i8::MAX as i64 {35self.cast(&DataType::Int8)36} else if cfg!(feature = "dtype-i16")37&& min >= i16::MIN as i6438&& max <= i16::MAX as i6439{40self.cast(&DataType::Int16)41} else if min >= i32::MIN as i64 && max <= i32::MAX as i64 {42self.cast(&DataType::Int32)43} else {44Ok(self.clone())45}46}47}48}495051