polars_core/frame/column/
arithmetic.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
use num_traits::{Num, NumCast};
use polars_error::PolarsResult;

use super::{Column, ScalarColumn, Series};

fn num_op_with_broadcast<T: Num + NumCast, F: Fn(&Series, T) -> Series>(
    c: &'_ Column,
    n: T,
    op: F,
) -> Column {
    match c {
        Column::Series(s) => op(s, n).into(),
        // @partition-opt
        Column::Partitioned(s) => op(s.as_materialized_series(), n).into(),
        Column::Scalar(s) => {
            ScalarColumn::from_single_value_series(op(&s.as_single_value_series(), n), s.len())
                .into()
        },
    }
}

macro_rules! broadcastable_ops {
    ($(($trait:ident, $op:ident))+) => {
        $(
        impl std::ops::$trait for Column {
            type Output = PolarsResult<Column>;

            #[inline]
            fn $op(self, rhs: Self) -> Self::Output {
                self.try_apply_broadcasting_binary_elementwise(&rhs, |l, r| l.$op(r))
            }
        }

        impl std::ops::$trait for &Column {
            type Output = PolarsResult<Column>;

            #[inline]
            fn $op(self, rhs: Self) -> Self::Output {
                self.try_apply_broadcasting_binary_elementwise(rhs, |l, r| l.$op(r))
            }
        }
        )+
    }
}

macro_rules! broadcastable_num_ops {
    ($(($trait:ident, $op:ident))+) => {
        $(
        impl<T> std::ops::$trait::<T> for Column
        where
            T: Num + NumCast,
        {
            type Output = Self;

            #[inline]
            fn $op(self, rhs: T) -> Self::Output {
                num_op_with_broadcast(&self, rhs, |l, r| l.$op(r))
            }
        }

        impl<T> std::ops::$trait::<T> for &Column
        where
            T: Num + NumCast,
        {
            type Output = Column;

            #[inline]
            fn $op(self, rhs: T) -> Self::Output {
                num_op_with_broadcast(self, rhs, |l, r| l.$op(r))
            }
        }
        )+
    };
}

broadcastable_ops! {
    (Add, add)
    (Sub, sub)
    (Mul, mul)
    (Div, div)
    (Rem, rem)
    (BitAnd, bitand)
    (BitOr, bitor)
    (BitXor, bitxor)
}

broadcastable_num_ops! {
    (Add, add)
    (Sub, sub)
    (Mul, mul)
    (Div, div)
    (Rem, rem)
}