jorgecarleitao commented on a change in pull request #9509:
URL: https://github.com/apache/arrow/pull/9509#discussion_r577283407



##########
File path: rust/datafusion/src/physical_plan/functions.rs
##########
@@ -617,48 +670,137 @@ mod tests {
     };
     use arrow::{
         array::{
-            ArrayRef, FixedSizeListArray, Float64Array, Int32Array, 
StringArray,
+            Array, ArrayRef, FixedSizeListArray, Float64Array, Int32Array, 
StringArray,
             UInt32Array, UInt64Array,
         },
         datatypes::Field,
         record_batch::RecordBatch,
     };
 
-    fn generic_test_math(value: ScalarValue, expected: &str) -> Result<()> {
-        // any type works here: we evaluate against a literal of `value`
-        let schema = Schema::new(vec![Field::new("a", DataType::Int32, 
false)]);
-        let columns: Vec<ArrayRef> = vec![Arc::new(Int32Array::from(vec![1]))];
-
-        let arg = lit(value);
-
-        let expr = create_physical_expr(&BuiltinScalarFunction::Exp, &[arg], 
&schema)?;
-
-        // type is correct
-        assert_eq!(expr.data_type(&schema)?, DataType::Float64);
-
-        // evaluate works
-        let batch = RecordBatch::try_new(Arc::new(schema.clone()), columns)?;
-        let result = expr.evaluate(&batch)?.into_array(batch.num_rows());
-
-        // downcast works
-        let result = result.as_any().downcast_ref::<Float64Array>().unwrap();
-
-        // value is correct
-        assert_eq!(result.value(0).to_string(), expected);
-
-        Ok(())
+    /// $FUNC function to test
+    /// $ARGS arguments (vec) to pass to function
+    /// $EXPECTED a Result<Option<$EXPECTED_TYPE>> where Result allows testing 
errors and Option allows testing Null
+    /// $EXPECTED_TYPE is the expected value type
+    /// $DATA_TYPE is the function to test result type
+    /// $ARRAY_TYPE is the column type after function applied
+    macro_rules! test_function {
+        ($FUNC:ident, $ARGS:expr, $EXPECTED:expr, $EXPECTED_TYPE:ty, 
$DATA_TYPE: ident, $ARRAY_TYPE:ident) => {
+            println!("{:?}", BuiltinScalarFunction::$FUNC);

Review comment:
       is this `println!` intended?

##########
File path: rust/arrow/src/compute/kernels/bit_length.rs
##########
@@ -0,0 +1,208 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Defines kernel for length of a string array
+
+use crate::{array::*, buffer::Buffer};
+use crate::{
+    datatypes::DataType,
+    error::{ArrowError, Result},
+};
+use std::sync::Arc;
+
+fn bit_length_string<OffsetSize>(array: &Array, data_type: DataType) -> 
ArrayRef
+where
+    OffsetSize: OffsetSizeTrait,
+{
+    // note: offsets are stored as u8, but they can be interpreted as 
OffsetSize
+    let offsets = &array.data_ref().buffers()[0];
+    // this is a 30% improvement over iterating over u8s and building 
OffsetSize, which
+    // justifies the usage of `unsafe`.
+    let slice: &[OffsetSize] =
+        &unsafe { offsets.typed_data::<OffsetSize>() }[array.offset()..];
+
+    let bit_size = OffsetSize::from_usize(8).unwrap();
+    let lengths = slice
+        .windows(2)
+        .map(|offset| (offset[1] - offset[0]) * bit_size);
+
+    // JUSTIFICATION
+    //  Benefit
+    //      ~60% speedup
+    //  Soundness
+    //      `values` is an iterator with a known size.
+    let buffer = unsafe { Buffer::from_trusted_len_iter(lengths) };
+

Review comment:
       Isn't this a copy of length, with a single difference, that we multiply 
the lengths by `bit_size`?
   
   If that is the case, can we create a generic or something that avoids code 
duplication? Copy-pasting code like this is IMO an unnecessary maintenance 
burden.

##########
File path: rust/datafusion/src/physical_plan/string_expressions.rs
##########
@@ -115,6 +119,40 @@ where
     }
 }
 
+/// Returns number of characters in the string.
+/// character_length_i32('josé') = 4
+pub fn character_length_i32(args: &[ArrayRef]) -> Result<ArrayRef> {
+    let string_array: &GenericStringArray<i32> = args[0]
+        .as_any()
+        .downcast_ref::<GenericStringArray<i32>>()
+        .unwrap();
+
+    // first map is the iterator, second is for the `Option<_>`
+    let result = string_array
+        .iter()
+        .map(|x| x.map(|x: &str| x.graphemes(true).count() as i32))
+        .collect::<Int32Array>();
+
+    Ok(Arc::new(result) as ArrayRef)
+}
+
+/// Returns number of characters in the string.
+/// character_length_i64('josé') = 4
+pub fn character_length_i64(args: &[ArrayRef]) -> Result<ArrayRef> {

Review comment:
       I think that this code can be reduced to a single generic. Something 
like this (untested):
   
   ```rust
   pub fn character_length<T: ArrowNativeType>(args: &[ArrayRef]) -> 
Result<ArrayRef> 
   where 
   T::Native: StringOffsetSizeTrait {
       let string_array: &GenericStringArray<T::Native> = args[0]
           .as_any()
           .downcast_ref::<GenericStringArray<T::Native>>()
           .unwrap();
       
        string_array
           .iter()
           .map(|x| x.map(|x: &str| 
T::Native::from_usize(x.graphemes(true).count())).unwrap())
           .collect()
   }
   ```
   




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


Reply via email to