json.rs

Overview

The [json.rs](/projects/287/67742) file provides a JSON serializer implementation optimized for performance and flexibility. It adapts and extends functionality from Serde JSON's serialization logic (`src/value/ser.rs`) to fit within the project's modular serialization framework. The serializer converts Rust data structures implementing `serde::Serialize` into JSON text by writing directly to a generic output writer with support for customizable formatting (compact or pretty-printed).

Key features include:

This file acts as a core serialization utility that other system components use to convert data into JSON format, enabling output to various sinks (files, network buffers, etc.) while maintaining high throughput and minimal allocations.


Detailed Documentation

Structs


Serializer<W, F = CompactFormatter>

A generic JSON serializer that writes serialized data to a writer `W` with formatting controlled by a formatter `F`.

use json::Serializer;
use crate::serialize::writer::formatter::PrettyFormatter;

let writer = ...; // Some buffer implementing WriteExt + BufMut
let mut ser = Serializer::new(writer); // Compact JSON serializer

// Or for pretty-printed JSON:
let mut pretty_ser = Serializer::pretty(writer);

// Serialize a serializable value
value.serialize(&mut ser)?;

Method

Description

`new(writer: W) -> Self`

Creates a new serializer with the compact formatter.

`pretty(writer: W) -> Self`

Creates a new serializer with the pretty formatter.

`with_formatter(writer: W, formatter: F) -> Self`

Creates a serializer with a custom formatter.


Compound<'a, W, F>

Helper struct used during serialization of sequences (arrays) and maps (objects).


MapKeySerializer<'a, W, F>

A specialized serializer used exclusively to serialize map keys as JSON strings.


Enum


State

Represents the state of serialization within compound structures:

Used to determine when to insert commas or other separators.


Trait Implementations


impl<W, F> ser::Serializer for &mut Serializer<W, F>

Implements Serde's `Serializer` trait for mutable references to `Serializer`, enabling seamless serialization of Rust data structures to JSON.


impl<W, F> ser::SerializeSeq for Compound<'_, W, F>

Allows serialization of JSON arrays.


impl<W, F> ser::SerializeMap for Compound<'_, W, F>

Allows serialization of JSON objects.


impl<W, F> ser::Serializer for MapKeySerializer<'_, W, F>

A restricted serializer for map keys that only supports string serialization.


Functions


set_str_formatter_fn()

Sets the string escaping function pointer (`STR_FORMATTER_FN`) at runtime based on detected CPU features, enabling selection between AVX512 and legacy implementations.


format_escaped_str<W>(writer: &mut W, value: &str)

Writes a JSON-escaped string to the writer using the fastest available implementation:


to_writer<W, T>(writer: W, value: &T) -> Result<()>

Serializes a serializable value `value` to the provided writer using the compact formatter.


to_writer_pretty<W, T>(writer: W, value: &T) -> Result<()>

Serializes a value to the provided writer using the pretty formatter.


Macros


reserve_str!($writer, $value)

Reserves buffer space in the writer for an escaped string, estimating the required capacity as `value.len() * 8 + 32`.


Important Implementation Details and Algorithms


Interactions with Other System Components


Usage Examples

use serde::Serialize;
use crate::serialize::writer::buffer::Buffer; // Hypothetical writer buffer
use json::{Serializer, to_writer, to_writer_pretty};

#[derive(Serialize)]
struct Person {
    name: String,
    age: u32,
}

fn serialize_person_compact(person: &Person) -> Result<Vec<u8>, serde_json::error::Error> {
    let mut buffer = Buffer::new();
    to_writer(&mut buffer, person)?;
    Ok(buffer.into_inner())
}

fn serialize_person_pretty(person: &Person) -> Result<Vec<u8>, serde_json::error::Error> {
    let mut buffer = Buffer::new();
    to_writer_pretty(&mut buffer, person)?;
    Ok(buffer.into_inner())
}

Visual Diagram

flowchart TD
    Serializer -->|uses| Formatter
    Serializer -->|writes to| Writer[WriteExt + BufMut]
    Serializer -->|creates| Compound
    Compound -->|manages| State{First / Rest}
    Compound -->|implements| SerializeSeq
    Compound -->|implements| SerializeMap
    SerializeMap -->|uses| MapKeySerializer
    MapKeySerializer -->|serialize_str only| Serializer

    Formatter --> CompactFormatter
    Formatter --> PrettyFormatter

    Serializer --> format_escaped_str
    format_escaped_str -->|calls| SIMD_String_Escaping

    to_writer --> Serializer
    to_writer_pretty --> Serializer

Summary

The [json.rs](/projects/287/67742) file is a core JSON serialization module tailored for high-performance and configurable formatting. It integrates with Serde's serialization traits and the project's writer and formatter abstractions, providing a robust and optimized pathway from Rust data structures to JSON text output. Its design balances minimalism (by marking unsupported operations as unreachable) and performance (leveraging SIMD string escaping and zero-copy buffer writes). This file is foundational for any system components requiring JSON serialization capabilities.