osipovartem commented on code in PR #11409:
URL: https://github.com/apache/arrow-rs/pull/11409#discussion_r4703336251


##########
parquet-variant-json/src/from_json.rs:
##########
@@ -70,46 +76,380 @@ pub trait JsonToVariant {
 
 impl<T: VariantBuilderExt> JsonToVariant for T {
     fn append_json(&mut self, json: &str) -> Result<(), ArrowError> {
-        let json: Value = serde_json::from_str(json)
-            .map_err(|e| ArrowError::InvalidArgumentError(format!("JSON format 
error: {e}")))?;
-
-        append_json(&json, self)?;
-        Ok(())
+        JsonParser::new(json).parse(self)
     }
 }
 
 fn variant_from_number<'m, 'v>(n: &Number) -> Result<Variant<'m, 'v>, 
ArrowError> {
     if let Some(i) = n.as_i64() {
-        // Find minimum Integer width to fit
-        if i as i8 as i64 == i {
-            Ok((i as i8).into())
-        } else if i as i16 as i64 == i {
-            Ok((i as i16).into())
-        } else if i as i32 as i64 == i {
-            Ok((i as i32).into())
+        Ok(variant_from_i64(i))
+    } else {
+        n.as_f64().map(Variant::from).ok_or_else(|| {
+            ArrowError::InvalidArgumentError(format!("Failed to parse {n} as 
number"))
+        })
+    }
+}
+
+fn variant_from_i64(i: i64) -> Variant<'static, 'static> {
+    if i as i8 as i64 == i {
+        (i as i8).into()
+    } else if i as i16 as i64 == i {
+        (i as i16).into()
+    } else if i as i32 as i64 == i {
+        (i as i32).into()
+    } else {
+        i.into()
+    }
+}
+
+fn variant_from_number_text(value: &str) -> Result<Variant<'static, 'static>, 
ArrowError> {
+    if value != "-0"
+        && !value.contains(['.', 'e', 'E'])
+        && let Ok(integer) = value.parse::<i64>()
+    {
+        return Ok(variant_from_i64(integer));
+    }
+
+    let number: Number = serde_json::from_str(value).map_err(|error| {
+        ArrowError::InvalidArgumentError(format!(
+            "Failed to parse {value} as finite number: {error}"
+        ))
+    })?;
+    variant_from_number(&number)
+}
+
+fn first_json_control(bytes: &[u8]) -> Option<usize> {
+    const SUB: u64 = 0x2020_2020_2020_2020;
+    const HIGH_BITS: u64 = 0x8080_8080_8080_8080;
+    let (chunks, remainder) = bytes.as_chunks::<8>();
+    let remainder_start = chunks.len() * 8;
+    for (chunk_index, chunk) in chunks.iter().enumerate() {
+        let word = u64::from_ne_bytes(*chunk);
+        // The word test may overreport a hit; locate and confirm the control 
byte.
+        if word.wrapping_sub(SUB) & !word & HIGH_BITS != 0
+            && let Some(position) = chunk.iter().position(|byte| *byte < 0x20)
+        {
+            return Some(chunk_index * 8 + position);
+        }
+    }
+    remainder
+        .iter()
+        .position(|byte| *byte < 0x20)
+        .map(|position| remainder_start + position)
+}
+
+struct JsonParser<'a> {
+    input: &'a str,
+    bytes: &'a [u8],
+    offset: usize,
+}
+
+impl<'a> JsonParser<'a> {
+    fn new(input: &'a str) -> Self {
+        Self {
+            input,
+            bytes: input.as_bytes(),
+            offset: 0,
+        }
+    }
+
+    fn parse(&mut self, builder: &mut impl VariantBuilderExt) -> Result<(), 
ArrowError> {
+        self.skip_whitespace();
+        self.parse_value(builder, 0)?;
+        debug_assert_eq!(self.offset, self.bytes.len());
+        Ok(())
+    }
+
+    fn parse_value(
+        &mut self,
+        builder: &mut impl VariantBuilderExt,
+        depth: usize,
+    ) -> Result<(), ArrowError> {
+        if depth > MAX_JSON_DEPTH {
+            return self.error("recursion limit exceeded");
+        }
+

Review Comment:
   Both array and object entry now check the shared `MAX_NESTING_DEPTH` limit 
before reading children. The regression accepts 128 containers and rejects 129, 
including empty `[]` and `{}` leaves.



##########
parquet-variant-json/src/from_json.rs:
##########
@@ -70,46 +76,380 @@ pub trait JsonToVariant {
 
 impl<T: VariantBuilderExt> JsonToVariant for T {
     fn append_json(&mut self, json: &str) -> Result<(), ArrowError> {
-        let json: Value = serde_json::from_str(json)
-            .map_err(|e| ArrowError::InvalidArgumentError(format!("JSON format 
error: {e}")))?;
-
-        append_json(&json, self)?;
-        Ok(())
+        JsonParser::new(json).parse(self)
     }
 }
 
 fn variant_from_number<'m, 'v>(n: &Number) -> Result<Variant<'m, 'v>, 
ArrowError> {
     if let Some(i) = n.as_i64() {
-        // Find minimum Integer width to fit
-        if i as i8 as i64 == i {
-            Ok((i as i8).into())
-        } else if i as i16 as i64 == i {
-            Ok((i as i16).into())
-        } else if i as i32 as i64 == i {
-            Ok((i as i32).into())
+        Ok(variant_from_i64(i))
+    } else {
+        n.as_f64().map(Variant::from).ok_or_else(|| {
+            ArrowError::InvalidArgumentError(format!("Failed to parse {n} as 
number"))
+        })
+    }
+}
+
+fn variant_from_i64(i: i64) -> Variant<'static, 'static> {
+    if i as i8 as i64 == i {
+        (i as i8).into()
+    } else if i as i16 as i64 == i {
+        (i as i16).into()
+    } else if i as i32 as i64 == i {
+        (i as i32).into()
+    } else {
+        i.into()
+    }
+}
+
+fn variant_from_number_text(value: &str) -> Result<Variant<'static, 'static>, 
ArrowError> {
+    if value != "-0"
+        && !value.contains(['.', 'e', 'E'])
+        && let Ok(integer) = value.parse::<i64>()
+    {
+        return Ok(variant_from_i64(integer));
+    }
+
+    let number: Number = serde_json::from_str(value).map_err(|error| {
+        ArrowError::InvalidArgumentError(format!(
+            "Failed to parse {value} as finite number: {error}"
+        ))
+    })?;
+    variant_from_number(&number)
+}

Review Comment:
   The serde reparse is gone. Non-integer tokens now use `lexical-core` with a 
finite-value check; integer `-0` takes the normal integer path and the 
regression expects `Int8(0)`.



##########
parquet-variant-json/src/from_json.rs:
##########
@@ -667,4 +1043,136 @@ mod test {
         }
         .run()
     }
+
+    #[test]
+    fn test_json_to_variant_escaped_strings() -> Result<(), ArrowError> {
+        let json = r#"{"line\nkey":"quote: \"; slash: \\; unicode: \u2764"}"#;
+        let mut variant_builder = VariantBuilder::new();
+        variant_builder.append_json(json)?;
+        let (metadata, value) = variant_builder.finish();
+        let variant = Variant::try_new(&metadata, &value)?;
+        assert_eq!(
+            variant.to_json_string()?,
+            "{\"line\\nkey\":\"quote: \\\"; slash: \\\\; unicode: ❤\"}"
+        );
+        Ok(())
+    }
+
+    #[test]
+    fn test_json_to_variant_rejects_invalid_json() {
+        let invalid = [
+            "",
+            "nul",
+            "True",
+            "[",
+            "{",
+            "[1,]",
+            "[1 2]",
+            "[1,,2]",
+            "{\"a\":1,}",
+            "{\"a\" 1}",
+            "{\"a\":1 \"b\":2}",
+            concat!("{", "a:1}"),
+            "01",
+            "-01",
+            "+1",
+            ".1",
+            "1.",
+            "1e",
+            "1e+",
+            "true false",
+            "\"unterminated",
+            "\"bad\\xescape\"",
+            "\"bad\\u12x4\"",
+            "\"lone high surrogate: \\ud800\"",
+            "\"lone low surrogate: \\udc00\"",
+        ];
+
+        for json in invalid {
+            let mut builder = VariantBuilder::new();
+            assert!(builder.append_json(json).is_err(), "accepted {json:?}");
+        }
+    }

Review Comment:
   The consolidated table checks rejection and builder rollback for every 
invalid input, including short and long raw control bytes, `1e400`, and 
`1x`/`[]x`/`{}x`.



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