polars_arrow/compute/
bitwise.rs

1//! Contains bitwise operators: [`or`], [`and`], [`xor`] and [`not`].
2use std::ops::{BitAnd, BitOr, BitXor, Not};
3
4use crate::array::PrimitiveArray;
5use crate::compute::arity::{binary, unary};
6use crate::types::NativeType;
7
8/// Performs `OR` operation on two [`PrimitiveArray`]s.
9/// # Panic
10/// This function errors when the arrays have different lengths.
11pub fn or<T>(lhs: &PrimitiveArray<T>, rhs: &PrimitiveArray<T>) -> PrimitiveArray<T>
12where
13    T: NativeType + BitOr<Output = T>,
14{
15    binary(lhs, rhs, lhs.dtype().clone(), |a, b| a | b)
16}
17
18/// Performs `XOR` operation between two [`PrimitiveArray`]s.
19/// # Panic
20/// This function errors when the arrays have different lengths.
21pub fn xor<T>(lhs: &PrimitiveArray<T>, rhs: &PrimitiveArray<T>) -> PrimitiveArray<T>
22where
23    T: NativeType + BitXor<Output = T>,
24{
25    binary(lhs, rhs, lhs.dtype().clone(), |a, b| a ^ b)
26}
27
28/// Performs `AND` operation on two [`PrimitiveArray`]s.
29/// # Panic
30/// This function panics when the arrays have different lengths.
31pub fn and<T>(lhs: &PrimitiveArray<T>, rhs: &PrimitiveArray<T>) -> PrimitiveArray<T>
32where
33    T: NativeType + BitAnd<Output = T>,
34{
35    binary(lhs, rhs, lhs.dtype().clone(), |a, b| a & b)
36}
37
38/// Returns a new [`PrimitiveArray`] with the bitwise `not`.
39pub fn not<T>(array: &PrimitiveArray<T>) -> PrimitiveArray<T>
40where
41    T: NativeType + Not<Output = T>,
42{
43    let op = move |a: T| !a;
44    unary(array, op, array.dtype().clone())
45}
46
47/// Performs `OR` operation between a [`PrimitiveArray`] and scalar.
48/// # Panic
49/// This function errors when the arrays have different lengths.
50pub fn or_scalar<T>(lhs: &PrimitiveArray<T>, rhs: &T) -> PrimitiveArray<T>
51where
52    T: NativeType + BitOr<Output = T>,
53{
54    unary(lhs, |a| a | *rhs, lhs.dtype().clone())
55}
56
57/// Performs `XOR` operation between a [`PrimitiveArray`] and scalar.
58/// # Panic
59/// This function errors when the arrays have different lengths.
60pub fn xor_scalar<T>(lhs: &PrimitiveArray<T>, rhs: &T) -> PrimitiveArray<T>
61where
62    T: NativeType + BitXor<Output = T>,
63{
64    unary(lhs, |a| a ^ *rhs, lhs.dtype().clone())
65}
66
67/// Performs `AND` operation between a [`PrimitiveArray`] and scalar.
68/// # Panic
69/// This function panics when the arrays have different lengths.
70pub fn and_scalar<T>(lhs: &PrimitiveArray<T>, rhs: &T) -> PrimitiveArray<T>
71where
72    T: NativeType + BitAnd<Output = T>,
73{
74    unary(lhs, |a| a & *rhs, lhs.dtype().clone())
75}