liukun4515 commented on code in PR #2649:
URL: https://github.com/apache/arrow-rs/pull/2649#discussion_r963202658


##########
arrow/src/compute/kernels/cast.rs:
##########
@@ -1456,21 +1621,62 @@ where
 }
 
 /// Convert Array into a PrimitiveArray of type, and apply numeric cast
-fn cast_numeric_arrays<FROM, TO>(from: &ArrayRef) -> Result<ArrayRef>
+fn cast_numeric_arrays<FROM, TO>(
+    from: &ArrayRef,
+    cast_options: &CastOptions,
+) -> Result<ArrayRef>
 where
     FROM: ArrowNumericType,
     TO: ArrowNumericType,
     FROM::Native: num::NumCast,
     TO::Native: num::NumCast,
 {
-    Ok(Arc::new(numeric_cast::<FROM, TO>(
-        from.as_any()
-            .downcast_ref::<PrimitiveArray<FROM>>()
-            .unwrap(),
-    )))
+    if cast_options.safe {
+        // If the value can't be casted to the `TO::Native`, return null
+        Ok(Arc::new(numeric_cast::<FROM, TO>(
+            from.as_any()
+                .downcast_ref::<PrimitiveArray<FROM>>()
+                .unwrap(),
+        )))
+    } else {
+        // If the value can't be casted to the `TO::Native`, return error
+        Ok(Arc::new(numeric_cast_with_error::<FROM, TO>(
+            from.as_any()
+                .downcast_ref::<PrimitiveArray<FROM>>()
+                .unwrap(),
+        )?))
+    }
 }
 
-/// Natural cast between numeric types
+// Natural cast between numeric types
+// If the value of T can't be casted to R, will throw error
+fn numeric_cast_with_error<T, R>(from: &PrimitiveArray<T>) -> 
Result<PrimitiveArray<R>>
+where
+    T: ArrowNumericType,
+    R: ArrowNumericType,
+    T::Native: num::NumCast,
+    R::Native: num::NumCast,
+{
+    let iter = from
+        .iter()
+        .map(|v| match v {
+            None => Ok(None),
+            Some(value) => match num::cast::cast::<T::Native, 
R::Native>(value) {
+                None => Err(ArrowError::CastError(format!(
+                    "Can't cast value {:?} to type {}",
+                    value,
+                    R::DATA_TYPE
+                ))),
+                Some(v) => Ok(Some(v)),
+            },
+        })
+        .collect::<Result<Vec<Option<R::Native>>>>()?;
+
+    Ok(unsafe { PrimitiveArray::<R>::from_trusted_len_iter(iter) })

Review Comment:
   Do you mean add a new api `try_xxx` for `PrimitiveArray`?



-- 
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.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to