sdf-jkl commented on code in PR #12465:
URL: https://github.com/apache/arrow-rs/pull/12465#discussion_r4804136928


##########
parquet-variant-compute/src/type_conversion.rs:
##########
@@ -707,6 +711,55 @@ pub(crate) fn variant_to_boolean(
     }
 }
 
+#[inline(never)]
+fn write_float_to_string<F: Float>(out: &mut String, f: F) {
+    let mut buffer = ryu::Buffer::new();
+    out.push_str(buffer.format(f));
+}
+
+#[inline(never)]
+fn write_lexical_to_string<N: lexical_core::ToLexical>(out: &mut String, n: N) 
{
+    // i64::FORMATTED_SIZE is the upper bound for all integer types we support
+    // (i8/i16/i32/i64). With power-of-two feature it's 128, otherwise 20.
+    // We can't use N::FORMATTED_SIZE in a generic function 
(generic_const_exprs).
+    let mut buf = [0u8; i64::FORMATTED_SIZE];
+    let written = lexical_core::write(n, &mut buf);
+    // Lexical core produces valid UTF-8
+    out.push_str(unsafe { std::str::from_utf8_unchecked(written) });
+}
+
+#[inline(never)]
+fn write_decimal_to_string<V: DecimalNativeType>(out: &mut String, value: V, 
scale: u8) {
+    datatypes::write_decimal(out, value, scale as _).expect("writing to string 
shouldn't fail");
+}

Review Comment:
   Sorry, I missed this last round. The spec puts ints and decimals in one 
Exact Numeric class and uses this exact example: an int8 1 ["should behave the 
same as a decimal16 with scale 2 and unscaled value 
100"](https://github.com/apache/parquet-format/blob/68cd231f6049546839e2a61093968e1d8d652a82/VariantEncoding.md?plain=1#L438).
 Here they come out as `"1"` and `"1.00"`.
   
   It also makes the result depend on storage. `shred_variant` accepts ints for 
a decimal `typed_value`, so Int8 `[1, 2]` reads back as `["1", "2"]` unshredded 
and `["1.00", "2.00"]` after shredding into `Decimal32(9, 2)`.
   
   `VariantDecimal`'s `Display` already strips trailing zeros, and Spark does 
the same in `VariantGet.cast` (`variant_get(cast(1.00::decimal(3,2) as 
variant), '$', 'string')` returns `1`). #12302 proposes the same rule for 
canonical Variant bytes (decimals lose their trailing zeros), and it follows 
the equivalence-class point you raised in 
[#10313](https://github.com/apache/arrow-rs/pull/10313#discussion_r3841121078). 
Trimming after `write_decimal` matches `Display` without its allocation:
   
   ```suggestion
   /// Strips trailing fractional zeros. The scale of a Variant decimal is 
physical, so equal
   /// Exact Numeric values (int8 1, decimal 1.00) should produce the same 
string.
   #[inline(never)]
   fn write_decimal_to_string<V: DecimalNativeType>(out: &mut String, value: V, 
scale: u8) {
       datatypes::write_decimal(out, value, scale as _).expect("writing to 
string shouldn't fail");
       if scale > 0 {
           let len = out.trim_end_matches('0').trim_end_matches('.').len();
           out.truncate(len);
       }
   }
   ```



##########
parquet-variant-compute/src/variant_to_arrow.rs:
##########
@@ -1755,13 +1828,17 @@ mod tests {
         make_primitive_variant_to_arrow_row_builder, 
make_typed_variant_to_arrow_row_builder,
     };
     use crate::type_conversion::VariantCastMode;
+    use crate::{GetOptions, cast_to_variant, variant_get};

Review Comment:
   Needed by the test below.
   
   ```suggestion
       use crate::{GetOptions, cast_to_variant, shred_variant, variant_get};
   ```



##########
parquet-variant-compute/src/variant_to_arrow.rs:
##########
@@ -1307,6 +1310,76 @@ define_variant_to_primitive_builder!(
     type_name: B::type_name()
 );
 
+pub(crate) struct VariantToStringArrowBuilder<'a, B: StringLikeArrayBuilder> {
+    builder: B,
+    cast_options: &'a CastOptions<'a>,
+    cast_mode: VariantCastMode,
+    buffer: String,
+}
+
+impl<'a, B: StringLikeArrayBuilder> VariantToStringArrowBuilder<'a, B> {
+    fn new(cast_options: &'a CastOptions<'a>, capacity: usize, cast_mode: 
VariantCastMode) -> Self {
+        Self {
+            builder: B::with_capacity(capacity),
+            cast_options,
+            cast_mode,
+            buffer: String::new(),
+        }
+    }
+
+    fn append_null(&mut self) -> Result<()> {
+        self.builder.append_null();
+        Ok(())
+    }
+
+    fn append_value(&mut self, value: &Variant<'_, '_>) -> Result<bool> {
+        let value = match value {
+            // short-circuit the common case of string-like variants to avoid 
the overhead of casting
+            Variant::String(value) => value,
+            Variant::ShortString(value) => value.as_str(),
+            Variant::Null => {
+                self.builder.append_null();
+                return Ok(false);
+            }
+            _ => return self.append_cast_value(value),
+        };
+
+        self.builder.append_value(value);
+        Ok(true)
+    }
+
+    fn append_cast_value(&mut self, value: &Variant<'_, '_>) -> Result<bool> {
+        self.buffer.clear();
+        match variant_cast_with_options(value, self.cast_options, |value| {
+            match self.cast_mode {
+                VariantCastMode::Get => match write_variant_to_string(&mut 
self.buffer, value) {
+                    true => Some(self.buffer.as_str()),
+                    false => None,
+                },
+                // this function only handle no-string variant, return None 
here because we don't support shred non-string to string.
+                VariantCastMode::Shred => None,
+            }
+        }) {
+            Ok(Some(value)) => {
+                self.builder.append_value(value);
+                Ok(true)
+            }
+            Ok(None) => {
+                self.builder.append_null();
+                Ok(false)
+            }
+            Err(_) => Err(ArrowError::CastError(format!(
+                "Failed to extract primitive of type {} from variant 
{value:?}",
+                B::type_name()
+            ))),
+        }
+    }

Review Comment:
   Makes sense, thanks!



##########
parquet-variant-compute/src/variant_to_arrow.rs:
##########
@@ -1932,4 +2009,115 @@ mod tests {
         let struct_array = 
struct_array.as_any().downcast_ref::<StructArray>().unwrap();
         assert!(struct_array.is_null(0));
     }
+
+    #[test]
+    fn test_variant_get_string_matches_cast_kernel() {
+        let inputs: Vec<ArrayRef> = vec![
+            Arc::new(BooleanArray::from(vec![Some(true), Some(false), None])),
+            Arc::new(Int8Array::from(vec![i8::MIN, i8::MAX])),
+            Arc::new(Int16Array::from(vec![i16::MIN, i16::MAX])),
+            Arc::new(Int32Array::from(vec![i32::MIN, i32::MAX])),
+            Arc::new(Int64Array::from(vec![i64::MIN, i64::MAX])),
+            Arc::new(Float32Array::from(vec![1.23, -0.0, 1e16, f32::NAN])),
+            Arc::new(Float64Array::from(vec![
+                0.1 + 0.2,
+                -0.0,
+                1e16,
+                f64::INFINITY,
+            ])),
+            Arc::new(
+                Decimal32Array::from(vec![-12345, 
5]).with_data_type(DataType::Decimal32(9, 2)),
+            ),
+            Arc::new(
+                Decimal64Array::from(vec![-12345, 
5]).with_data_type(DataType::Decimal64(18, 2)),
+            ),
+            Arc::new(
+                Decimal128Array::from(vec![-12345, 
5]).with_data_type(DataType::Decimal128(38, 2)),
+            ),
+            Arc::new(StringArray::from(vec![
+                "short",
+                "a string longer than the sixty three bytes a short string can 
hold",
+            ])),
+        ];
+        // Strict mode and non-default format options must not change the 
result.
+        let options = CastOptions {
+            safe: false,
+            format_options: FormatOptions::new()
+                .with_null("NULL")
+                .with_quoted_strings(true),
+        };
+
+        for input in &inputs {
+            let variants = 
ArrayRef::from(cast_to_variant(input.as_ref()).unwrap());
+            for target_type in [DataType::Utf8, DataType::LargeUtf8, 
DataType::Utf8View] {
+                let field = Arc::new(Field::new("result", target_type.clone(), 
true));
+                let get_options = GetOptions::new()
+                    .with_as_type(Some(field))
+                    .with_cast_options(options.clone());
+
+                let actual = variant_get(&variants, get_options).unwrap();
+                let expected = cast_with_options(input, &target_type, 
&options).unwrap();
+                assert_eq!(
+                    actual.as_ref(),
+                    expected.as_ref(),
+                    "{} -> {target_type}",
+                    input.data_type()
+                );
+            }
+        }
+    }
+
+    /// `Variant::Null` is NULL in both modes, other unsupported values are 
NULL or an error.

Review Comment:
   A test for the decimal change, covering shredded ints, plain ints, and 
decimals with trailing zeros:
   
   ```suggestion
       /// Equal Exact Numeric values give the same string, whatever the 
physical or shredded type.
       #[test]
       fn test_variant_get_string_exact_numeric_equivalence() {
           let ints = cast_to_variant(&Int8Array::from(vec![1, 0])).unwrap();
           let decimals = cast_to_variant(
               &Decimal32Array::from(vec![100, 0, 
150]).with_data_type(DataType::Decimal32(9, 2)),
           )
           .unwrap();
           let shredded = shred_variant(&ints, &DataType::Decimal32(9, 
2)).unwrap();
           let cases = [
               (shredded, vec!["1", "0"]),
               (ints, vec!["1", "0"]),
               (decimals, vec!["1", "0", "1.5"]),
           ];
           let field = Arc::new(Field::new("result", DataType::Utf8, true));
           for (input, expected) in cases {
               let options = 
GetOptions::new().with_as_type(Some(field.clone()));
               let actual = variant_get(&ArrayRef::from(input), 
options).unwrap();
               let expected: ArrayRef = Arc::new(StringArray::from(expected));
               assert_eq!(actual.as_ref(), expected.as_ref());
           }
       }
   
       /// `Variant::Null` is NULL in both modes, other unsupported values are 
NULL or an error.
   ```



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