yyjson.rs

Overview

This file provides a Rust-based JSON deserialization implementation using the [yyjson](https://github.com/ibireme/yyjson) library, a high-performance JSON parsing C library. The primary purpose of this module is to parse JSON text into Python objects efficiently by leveraging low-level memory operations and custom memory allocation strategies.

The module integrates with Python’s C API (via FFI) to create native Python data structures (`PyList`, `PyDict`, Python primitives) from JSON data, facilitating fast JSON deserialization in a Python environment (likely part of a Python extension module). It handles JSON arrays, objects, strings, numbers, booleans, and null values.


Detailed Documentation

Constants and Macros

Utility Functions


Enum: ElementType

Represents the JSON element types supported by yyjson.

Variant

Description

String

JSON string

Uint64

Unsigned 64-bit int

Int64

Signed 64-bit int

Double

Floating point number

Null

JSON null

True

JSON true boolean

False

JSON false boolean

Array

JSON array container

Object

JSON object container

Method: from_tag

fn from_tag(elem: *mut yyjson_val) -> Self

Converts a raw tag byte from a `yyjson_val` pointer to an `ElementType`. Unsafe, assumes valid tag.


Main Function: deserialize

pub(crate) fn deserialize(
    data: &'static str,
) -> Result<NonNull<pyo3_ffi::PyObject>, DeserializeError<'static>>

**Purpose:** Parses a JSON string into a Python object (`PyObject`) using `yyjson` and Python's C API.

**Parameters:**

**Returns:**

**Usage:** This function is the entry point to convert JSON text into Python native objects. It can be called by higher-level Python extension code to produce Python-compatible results.

**Implementation Highlights:**


Parsing Helper Functions

These functions convert leaf JSON types from `yyjson_val` pointers to Python objects.

Function

Description

`parse_yy_string`

Parses a JSON string into a Python `str` object.

`parse_yy_u64`

Parses an unsigned 64-bit integer.

`parse_yy_i64`

Parses a signed 64-bit integer.

`parse_yy_f64`

Parses a floating-point number.

Each returns a non-null pointer to a Python object.


Container Population Functions

These functions recursively traverse JSON arrays and objects, populating Python lists and dictionaries.

populate_yy_array

fn populate_yy_array(list: *mut pyo3_ffi::PyObject, elem: *mut yyjson_val)

populate_yy_object

fn populate_yy_object(dict: *mut pyo3_ffi::PyObject, elem: *mut yyjson_val)

Important Implementation Details


Interaction with Other Components

This file serves as the core JSON deserialization engine that transforms raw JSON input into Python-native representations for further use by the application.


Visual Diagram: Module Structure and Workflow

flowchart TD
    A[deserialize(data: &str)] --> B[Allocate buffer]
    B --> C[Initialize yyjson allocator]
    C --> D[yyjson_read_opts -> parse JSON]
    D -->|Success| E[Get root JSON value]
    E --> F{Is container?}
    F -->|No| G[Parse primitive types]
    F -->|Yes| H{Array or Object?}
    H -->|Array| I[Create Python list]
    I --> J[populate_yy_array]
    H -->|Object| K[Create Python dict]
    K --> L[populate_yy_object]
    G --> M[Return Python object]
    J --> M
    L --> M
    D -->|Fail| N[Handle error and free buffer]
    M --> O[Free buffer]
    O --> P[Return Python object or error]

Usage Example

use std::ptr::NonNull;

fn example_usage() -> Result<(), DeserializeError<'static>> {
    let json_str = r#"{"name": "Alice", "age": 30, "is_student": false}"#;
    let py_object: NonNull<pyo3_ffi::PyObject> = yyjson::deserialize(json_str)?;
    // py_object now points to a Python dictionary equivalent to the JSON input.
    // Further interaction would involve Python C API to use this object.
    Ok(())
}

Summary

The [yyjson.rs](/projects/287/67700) file implements a high-performance JSON deserializer that parses JSON strings into native Python objects by harnessing the `yyjson` C library and Python's C API. It uses unsafe Rust code for direct memory manipulation and provides recursive traversal of JSON structures to build Python lists and dictionaries. This module is central to the JSON deserialization workflow in the system, converting raw JSON data into usable Python representations efficiently and with detailed error handling.