Path: blob/main/crates/polars-core/src/frame/column/arithmetic.rs
8446 views
use num_traits::{Num, NumCast};1use polars_error::PolarsResult;23use super::{Column, ScalarColumn, Series};45fn num_op_with_broadcast<T: Num + NumCast, F: Fn(&Series, T) -> Series>(6c: &'_ Column,7n: T,8op: F,9) -> Column {10match c {11Column::Series(s) => op(s, n).into(),12Column::Scalar(s) => {13ScalarColumn::from_single_value_series(op(&s.as_single_value_series(), n), s.len())14.into()15},16}17}1819macro_rules! broadcastable_ops {20($(($trait:ident, $op:ident))+) => {21$(22impl std::ops::$trait for Column {23type Output = PolarsResult<Column>;2425#[inline]26fn $op(self, rhs: Self) -> Self::Output {27self.try_apply_broadcasting_binary_elementwise(&rhs, |l, r| l.$op(r))28}29}3031impl std::ops::$trait for &Column {32type Output = PolarsResult<Column>;3334#[inline]35fn $op(self, rhs: Self) -> Self::Output {36self.try_apply_broadcasting_binary_elementwise(rhs, |l, r| l.$op(r))37}38}39)+40}41}4243macro_rules! broadcastable_num_ops {44($(($trait:ident, $op:ident))+) => {45$(46impl<T> std::ops::$trait::<T> for Column47where48T: Num + NumCast,49{50type Output = Self;5152#[inline]53fn $op(self, rhs: T) -> Self::Output {54num_op_with_broadcast(&self, rhs, |l, r| l.$op(r))55}56}5758impl<T> std::ops::$trait::<T> for &Column59where60T: Num + NumCast,61{62type Output = Column;6364#[inline]65fn $op(self, rhs: T) -> Self::Output {66num_op_with_broadcast(self, rhs, |l, r| l.$op(r))67}68}69)+70};71}7273broadcastable_ops! {74(Add, add)75(Sub, sub)76(Mul, mul)77(Div, div)78(Rem, rem)79(BitAnd, bitand)80(BitOr, bitor)81(BitXor, bitxor)82}8384broadcastable_num_ops! {85(Add, add)86(Sub, sub)87(Mul, mul)88(Div, div)89(Rem, rem)90}919293