alamb commented on a change in pull request #9654: URL: https://github.com/apache/arrow/pull/9654#discussion_r590734861
########## File path: rust/datafusion/src/physical_plan/unicode_expressions.rs ########## @@ -0,0 +1,537 @@ +// 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. + +// Some of these functions reference the Postgres documentation +// or implementation to ensure compatibility and are subject to +// the Postgres license. + +//! Unicode expressions + +use std::any::type_name; +use std::cmp::Ordering; +use std::str::from_utf8; +use std::sync::Arc; + +use crate::error::{DataFusionError, Result}; +use arrow::{ + array::{ + ArrayRef, GenericStringArray, Int64Array, PrimitiveArray, StringOffsetSizeTrait, + }, + datatypes::{ArrowNativeType, ArrowPrimitiveType}, +}; +use hashbrown::HashMap; +use unicode_segmentation::UnicodeSegmentation; + +macro_rules! downcast_string_arg { + ($ARG:expr, $NAME:expr, $T:ident) => {{ + $ARG.as_any() + .downcast_ref::<GenericStringArray<T>>() + .ok_or_else(|| { + DataFusionError::Internal(format!( + "could not cast {} to {}", + $NAME, + type_name::<GenericStringArray<T>>() + )) + })? + }}; +} + +macro_rules! downcast_arg { + ($ARG:expr, $NAME:expr, $ARRAY_TYPE:ident) => {{ + $ARG.as_any().downcast_ref::<$ARRAY_TYPE>().ok_or_else(|| { + DataFusionError::Internal(format!( + "could not cast {} to {}", + $NAME, + type_name::<$ARRAY_TYPE>() + )) + })? + }}; +} + +/// Returns number of characters in the string. +/// character_length('josé') = 4 +pub fn character_length<T: ArrowPrimitiveType>(args: &[ArrayRef]) -> Result<ArrayRef> +where + T::Native: StringOffsetSizeTrait, +{ + let string_array: &GenericStringArray<T::Native> = args[0] + .as_any() + .downcast_ref::<GenericStringArray<T::Native>>() + .ok_or_else(|| { + DataFusionError::Internal("could not cast string to StringArray".to_string()) + })?; + + let result = string_array + .iter() + .map(|string| { + string.map(|string: &str| { + T::Native::from_usize(string.graphemes(true).count()).unwrap() + }) + }) + .collect::<PrimitiveArray<T>>(); + + Ok(Arc::new(result) as ArrayRef) +} + +/// Returns first n characters in the string, or when n is negative, returns all but last |n| characters. +/// left('abcde', 2) = 'ab' +pub fn left<T: StringOffsetSizeTrait>(args: &[ArrayRef]) -> Result<ArrayRef> { + let string_array = downcast_string_arg!(args[0], "string", T); + let n_array = downcast_arg!(args[1], "n", Int64Array); + + let result = string_array + .iter() + .zip(n_array.iter()) + .map(|(string, n)| match (string, n) { + (None, _) => None, + (_, None) => None, + (Some(string), Some(n)) => match n.cmp(&0) { + Ordering::Equal => Some(""), + Ordering::Greater => Some( + string + .grapheme_indices(true) + .nth(n as usize) + .map_or(string, |(i, _)| { + &from_utf8(&string.as_bytes()[..i]).unwrap() Review comment: I see -- I took a closer look and I see now that `graphemes` is an iterator -- so we are `clone()` ing an iterator, which I guess feels right to me -- the code has to effectively scan the input to figure out how many graphemes long it is and then scan it again to create the output. Sorry for my confusion! ---------------------------------------------------------------- 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