Skip to content

Commit

Permalink
feat: support bitwise shift left/right (#4148)
Browse files Browse the repository at this point in the history
* feat: support bitwise shift left/right

* ignore truncation

* add test when shifting by more than the number of bits
  • Loading branch information
Weijun-H authored Apr 28, 2023
1 parent 9fa8125 commit 67176f0
Showing 1 changed file with 56 additions and 0 deletions.
56 changes: 56 additions & 0 deletions arrow-arith/src/bitwise.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@

use crate::arity::{binary, unary};
use arrow_array::*;
use arrow_buffer::ArrowNativeType;
use arrow_schema::ArrowError;
use num::traits::{WrappingShl, WrappingShr};
use std::ops::{BitAnd, BitOr, BitXor, Not};

// The helper function for bitwise operation with two array
Expand Down Expand Up @@ -121,6 +123,38 @@ where
Ok(unary(array, |value| value ^ scalar))
}

/// Perform bitwise 'left << right' operation on two arrays. If either left or right value is null
/// then the result is also null.
pub fn bitwise_shift_left<T>(
left: &PrimitiveArray<T>,
right: &PrimitiveArray<T>,
) -> Result<PrimitiveArray<T>, ArrowError>
where
T: ArrowNumericType,
T::Native: WrappingShl<Output = T::Native>,
{
bitwise_op(left, right, |a, b| {
let b = b.as_usize();
a.wrapping_shl(b as u32)
})
}

/// Perform bitwise 'left >> right' operation on two arrays. If either left or right value is null
/// then the result is also null.
pub fn bitwise_shift_right<T>(
left: &PrimitiveArray<T>,
right: &PrimitiveArray<T>,
) -> Result<PrimitiveArray<T>, ArrowError>
where
T: ArrowNumericType,
T::Native: WrappingShr<Output = T::Native>,
{
bitwise_op(left, right, |a, b| {
let b = b.as_usize();
a.wrapping_shr(b as u32)
})
}

#[cfg(test)]
mod tests {
use super::*;
Expand All @@ -143,6 +177,28 @@ mod tests {
Ok(())
}

#[test]
fn test_bitwise_shift_left() {
let left = UInt64Array::from(vec![Some(1), Some(2), None, Some(4), Some(8)]);
let right =
UInt64Array::from(vec![Some(5), Some(10), Some(8), Some(12), Some(u64::MAX)]);
let expected =
UInt64Array::from(vec![Some(32), Some(2048), None, Some(16384), Some(0)]);
let result = bitwise_shift_left(&left, &right).unwrap();
assert_eq!(expected, result);
}

#[test]
fn test_bitwise_shift_right() {
let left =
UInt64Array::from(vec![Some(32), Some(2048), None, Some(16384), Some(3)]);
let right =
UInt64Array::from(vec![Some(5), Some(10), Some(8), Some(12), Some(65)]);
let expected = UInt64Array::from(vec![Some(1), Some(2), None, Some(4), Some(1)]);
let result = bitwise_shift_right(&left, &right).unwrap();
assert_eq!(expected, result);
}

#[test]
fn test_bitwise_and_array_scalar() {
// unsigned value
Expand Down

0 comments on commit 67176f0

Please sign in to comment.