unknowntpo commented on code in PR #20120:
URL: https://github.com/apache/datafusion/pull/20120#discussion_r2759030537


##########
datafusion/spark/src/function/map/string_to_map.rs:
##########
@@ -0,0 +1,225 @@
+// 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.
+
+use std::any::Any;
+use std::sync::Arc;
+
+use arrow::array::{Array, ArrayRef, StringArray, StringBuilder};
+use arrow::datatypes::{DataType, Field, FieldRef};
+use datafusion_common::{Result, internal_err};
+use datafusion_expr::{
+    ColumnarValue, ReturnFieldArgs, ScalarFunctionArgs, ScalarUDFImpl, 
Signature,
+    TypeSignature, Volatility,
+};
+use datafusion_functions::utils::make_scalar_function;
+
+use crate::function::map::utils::{
+    map_from_keys_values_offsets_nulls, map_type_from_key_value_types,
+};
+
+/// Spark-compatible `string_to_map` expression
+/// <https://spark.apache.org/docs/latest/api/sql/index.html#str_to_map>
+///
+/// Creates a map from a string by splitting on delimiters.
+/// string_to_map(text, pairDelim, keyValueDelim) -> Map<String, String>
+///
+/// - text: The input string
+/// - pairDelim: Delimiter between key-value pairs (default: ',')
+/// - keyValueDelim: Delimiter between key and value (default: ':')
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct SparkStringToMap {
+    signature: Signature,
+    aliases: Vec<String>,
+}
+
+impl Default for SparkStringToMap {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl SparkStringToMap {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::one_of(
+                vec![
+                    // string_to_map(text)
+                    TypeSignature::String(1),
+                    // string_to_map(text, pairDelim)
+                    TypeSignature::String(2),
+                    // string_to_map(text, pairDelim, keyValueDelim)
+                    TypeSignature::String(3),
+                ],
+                Volatility::Immutable,
+            ),
+            aliases: vec![String::from("str_to_map")],
+        }
+    }
+}
+
+impl ScalarUDFImpl for SparkStringToMap {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "string_to_map"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn aliases(&self) -> &[String] {
+        &self.aliases
+    }
+
+    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
+        internal_err!("return_field_from_args should be used instead")
+    }
+
+    fn return_field_from_args(&self, args: ReturnFieldArgs) -> 
Result<FieldRef> {
+        let nullable = args.arg_fields.iter().any(|f| f.is_nullable());
+        let map_type = map_type_from_key_value_types(&DataType::Utf8, 
&DataType::Utf8);
+        Ok(Arc::new(Field::new(self.name(), map_type, nullable)))
+    }
+
+    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> 
Result<ColumnarValue> {
+        make_scalar_function(string_to_map_inner, vec![])(&args.args)
+    }
+}
+
+fn string_to_map_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
+    let text_array = &args[0];
+
+    // Get delimiters with defaults
+    let pair_delim = if args.len() > 1 {
+        get_scalar_string(&args[1])?
+    } else {
+        ",".to_string()
+    };
+
+    let kv_delim = if args.len() > 2 {
+        get_scalar_string(&args[2])?
+    } else {
+        ":".to_string()
+    };
+
+    // Process each row
+    let text_array = text_array
+        .as_any()
+        .downcast_ref::<StringArray>()
+        .ok_or_else(|| {
+            datafusion_common::DataFusionError::Internal(
+                "Expected StringArray for text argument".to_string(),
+            )
+        })?;
+
+    let num_rows = text_array.len();
+    let mut keys_builder = StringBuilder::new();
+    let mut values_builder = StringBuilder::new();
+    let mut offsets: Vec<i32> = vec![0];
+    let mut null_buffer = vec![true; num_rows];
+
+    for row_idx in 0..num_rows {
+        if text_array.is_null(row_idx) {
+            null_buffer[row_idx] = false;
+            offsets.push(*offsets.last().unwrap());

Review Comment:
   No, last() will never return None here. The offsets vector is initialized 
with vec![0] (line 130), so it always has at least one element before the loop 
starts.
   
   I've refactor this and introduce a `current_offset` variable to avoid 
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.

To unsubscribe, e-mail: [email protected]

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


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to