Skip to main content

json_eval_rs/jsoneval/
json_parser.rs

1/// Hybrid SIMD-accelerated JSON parser with fallback to serde_json
2/// Uses simd-json's serde integration for direct deserialization into serde_json::Value
3use serde_json::Value;
4
5/// Parse JSON from a string slice using SIMD acceleration when possible
6/// Falls back to serde_json for compatibility
7#[inline]
8pub fn parse_json_str(json: &str) -> Result<Value, String> {
9    let mut bytes = json.as_bytes().to_vec();
10    parse_simd_bytes(&mut bytes).or_else(|_| {
11        serde_json::from_str(json).map_err(|e| e.to_string())
12    })
13}
14
15/// Parse JSON from bytes using SIMD acceleration when possible
16/// This is the fastest path as simd-json works on mutable byte slices
17#[inline]
18pub fn parse_json_bytes(mut bytes: Vec<u8>) -> Result<Value, String> {
19    parse_simd_bytes(&mut bytes).or_else(|_| {
20        serde_json::from_slice(&bytes).map_err(|e| e.to_string())
21    })
22}
23
24/// Internal SIMD parser — deserializes directly into serde_json::Value
25/// via simd-json's serde integration (no intermediate BorrowedValue)
26#[inline]
27fn parse_simd_bytes(bytes: &mut [u8]) -> Result<Value, String> {
28    simd_json::serde::from_slice(bytes).map_err(|e| e.to_string())
29}
30
31/// Read JSON file using SIMD acceleration
32/// Reads file into memory and uses fast SIMD parsing
33pub fn read_json_file(path: &str) -> Result<Value, String> {
34    let bytes = std::fs::read(path).map_err(|e| format!("Failed to read file {}: {}", path, e))?;
35    parse_json_bytes(bytes)
36}
37