xanderbailey commented on code in PR #21331: URL: https://github.com/apache/datafusion/pull/21331#discussion_r3035424596
########## datafusion/spark/src/function/string/encode.rs: ########## @@ -0,0 +1,500 @@ +// 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::sync::Arc; + +use arrow::array::{ArrayRef, AsArray, BinaryBuilder, StringArrayType}; +use arrow::datatypes::{DataType, Field, FieldRef}; +use datafusion_common::types::{ + NativeType, logical_binary, logical_null, logical_string, +}; +use datafusion_common::{Result, ScalarValue, exec_err}; +use datafusion_expr::{ + Coercion, ColumnarValue, ReturnFieldArgs, ScalarFunctionArgs, ScalarUDFImpl, + Signature, TypeSignatureClass, Volatility, +}; + +/// Spark-compatible `encode` expression. +/// Encodes a string or binary value into binary using the specified character encoding. +/// Binary input is interpreted as UTF-8 with lossy conversion (invalid bytes become U+FFFD). +/// +/// <https://spark.apache.org/docs/latest/api/sql/index.html#encode> +#[derive(Debug, PartialEq, Eq, Hash)] +pub struct SparkEncode { + signature: Signature, +} + +impl Default for SparkEncode { + fn default() -> Self { + Self::new() + } +} + +impl SparkEncode { + pub fn new() -> Self { + Self { + signature: Signature::coercible( + vec![ + Coercion::new_implicit( + TypeSignatureClass::Native(logical_string()), + vec![ + TypeSignatureClass::Native(logical_null()), + TypeSignatureClass::Native(logical_binary()), + ], + NativeType::String, + ), + Coercion::new_implicit( + TypeSignatureClass::Native(logical_string()), + vec![TypeSignatureClass::Native(logical_null())], + NativeType::String, + ), + ], + Volatility::Immutable, + ), + } + } +} + +/// Encodes a single string value using the specified charset. +fn encode_string(s: &str, charset: &str) -> Result<Vec<u8>> { + match charset { + "UTF-8" | "UTF8" => Ok(s.as_bytes().to_vec()), + "US-ASCII" | "ASCII" => Ok(s + .chars() + .map(|c| if c.is_ascii() { c as u8 } else { b'?' }) + .collect()), + "ISO-8859-1" | "ISO88591" | "LATIN1" => Ok(s + .chars() + .map(|c| { + let cp = c as u32; + if cp > 255 { b'?' } else { cp as u8 } + }) + .collect()), + "UTF-16BE" | "UTF16BE" => { + let mut bytes = Vec::new(); + for code_unit in s.encode_utf16() { + bytes.extend_from_slice(&code_unit.to_be_bytes()); + } + Ok(bytes) + } + "UTF-16LE" | "UTF16LE" => { + let mut bytes = Vec::new(); + for code_unit in s.encode_utf16() { + bytes.extend_from_slice(&code_unit.to_le_bytes()); + } + Ok(bytes) + } + "UTF-16" | "UTF16" => { + // BOM (big-endian marker) followed by UTF-16BE encoded bytes + let mut bytes = vec![0xFE, 0xFF]; + for code_unit in s.encode_utf16() { + bytes.extend_from_slice(&code_unit.to_be_bytes()); + } + Ok(bytes) + } + _ => exec_err!( + "Unsupported charset for encode: '{}'. Supported: US-ASCII, ISO-8859-1, UTF-8, UTF-16, UTF-16BE, UTF-16LE", + charset + ), + } +} + +/// Encodes a string array using the given charset, producing a BinaryArray. +fn encode_array<'a, S: StringArrayType<'a>>( + string_array: &S, + charset: &str, +) -> Result<ArrayRef> { + let mut builder = + BinaryBuilder::with_capacity(string_array.len(), string_array.len() * 4); + for i in 0..string_array.len() { + if string_array.is_null(i) { + builder.append_null(); + } else { + let s = string_array.value(i); + let encoded = encode_string(s, charset)?; + builder.append_value(&encoded); + } + } + Ok(Arc::new(builder.finish())) +} + +/// Encodes a binary array using lossy UTF-8 conversion, then re-encodes with the given charset. +/// Invalid UTF-8 bytes become U+FFFD (replacement character), matching Spark behavior. +fn encode_binary_array<'a, B: arrow::array::BinaryArrayType<'a>>( + binary_array: &'a B, + charset: &str, +) -> Result<ArrayRef> { + let mut builder = + BinaryBuilder::with_capacity(binary_array.len(), binary_array.len() * 4); + for i in 0..binary_array.len() { + if binary_array.is_null(i) { + builder.append_null(); + } else { + let s = String::from_utf8_lossy(binary_array.value(i)); + let encoded = encode_string(&s, charset)?; + builder.append_value(&encoded); + } + } + Ok(Arc::new(builder.finish())) +} + +/// Dispatches to the correct typed array encoder based on the DataType. +fn encode_dispatch(arr: &ArrayRef, charset: &str) -> Result<ArrayRef> { + match arr.data_type() { + DataType::Utf8 => encode_array(&arr.as_string::<i32>(), charset), + DataType::LargeUtf8 => encode_array(&arr.as_string::<i64>(), charset), + DataType::Utf8View => encode_array(&arr.as_string_view(), charset), + DataType::Binary => encode_binary_array(&arr.as_binary::<i32>(), charset), + DataType::LargeBinary => encode_binary_array(&arr.as_binary::<i64>(), charset), + DataType::BinaryView => encode_binary_array(&arr.as_binary_view(), charset), + DataType::Null => { + let mut builder = BinaryBuilder::new(); + for _ in 0..arr.len() { + builder.append_null(); + } + Ok(Arc::new(builder.finish())) + } + dt => exec_err!("encode expects a string or binary argument, got {:?}", dt), + } +} + +/// Extracts a charset string from a ColumnarValue, normalizing to uppercase. +pub(crate) fn extract_charset(charset_arg: &ColumnarValue) -> Result<String> { Review Comment: Maybe until you need it? -- 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]
