formatter.rs
Overview
`formatter.rs` defines the core formatting logic for serializing data into textual representations, primarily targeting JSON-like output. It provides a `Formatter` trait that outlines methods for writing various primitive and structured data types (null, booleans, numbers, arrays, objects) to a generic output writer. Two concrete implementations of this trait are provided:
CompactFormatter: Produces minimal JSON output without extra whitespace.PrettyFormatter: Produces human-readable, pretty-printed JSON with indentation and line breaks.
This file is a foundational component in the serialization pipeline, converting in-memory data structures into well-formed JSON text efficiently.
Detailed Documentation
Imports and Macros
Uses
WriteExtfromcrate::serialize::writerto extend writing capabilities.Uses
bytes::BufMutfor buffer mutation.Uses external crates
itoap(integer to ASCII pointer writer) andryu(fast float formatting).debug_assert_has_capacity! macro asserts that the writer buffer has sufficient remaining capacity (>4 bytes) for performance and safety during unsafe writes.
Trait: Formatter
The `Formatter` trait defines the interface for writing JSON elements in a streaming fashion. It is generic over any writer `W` implementing `WriteExt` and `bytes::BufMut`. The trait methods write serialized representations of various data types and structural delimiters to the writer.
All methods return `io::Result<()>` to propagate any underlying I/O errors.
Methods
Method | Purpose | Parameters | Return | Notes / Usage Example |
|---|---|---|---|---|
`write_null` | Writes the JSON literal `null` | `writer: &mut W` | `io::Result<()>` | Writes `"null"` |
`write_bool` | Writes JSON boolean literals | `writer: &mut W`, `value: bool` | `io::Result<()>` | Writes `"true"` or `"false"` |
`write_i32` | Writes a 32-bit signed integer | `writer: &mut W`, [value: i32](/projects/287/68101) | `io::Result<()>` | Uses `itoap` for formatting |
`write_i64` | Writes a 64-bit signed integer | `writer: &mut W`, [value: i64](/projects/287/68101) | `io::Result<()>` | Uses `itoap` |
`write_u32` | Writes a 32-bit unsigned integer | `writer: &mut W`, [value: u32](/projects/287/68101) | `io::Result<()>` | Uses `itoap` |
`write_u64` | Writes a 64-bit unsigned integer | `writer: &mut W`, [value: u64](/projects/287/68101) | `io::Result<()>` | Uses `itoap` |
`write_f32` | Writes a 32-bit floating point number | `writer: &mut W`, [value: f32](/projects/287/68101) | `io::Result<()>` | Uses `ryu` for fast float formatting |
`write_f64` | Writes a 64-bit floating point number | `writer: &mut W`, [value: f64](/projects/287/68101) | `io::Result<()>` | Uses `ryu` |
`begin_array` | Writes [[](/projects/287/68169) to begin a JSON array | `writer: &mut W` | `io::Result<()>` | |
`end_array` | Writes []](/projects/287/68169) to end a JSON array | `writer: &mut W` | `io::Result<()>` | |
`begin_array_value` | Writes comma separator if not first array value | `writer: &mut W`, `first: bool` | `io::Result<()>` | Writes `,` if `first == false` |
`end_array_value` | Optional hook after writing an array value | `_writer: &mut W` | `io::Result<()>` | Default no-op |
`begin_object` | Writes `{` to begin a JSON object | `writer: &mut W` | `io::Result<()>` | |
`end_object` | Writes `}` to end a JSON object | `writer: &mut W` | `io::Result<()>` | |
`begin_object_key` | Writes comma if not first key in object | `writer: &mut W`, `first: bool` | `io::Result<()>` | Writes `,` if `first == false` |
`end_object_key` | Optional hook after a key | `_writer: &mut W` | `io::Result<()>` | Default no-op |
`begin_object_value` | Writes colon `:` separator between key and value | `writer: &mut W` | `io::Result<()>` | |
`end_object_value` | Optional hook after a value | `_writer: &mut W` | `io::Result<()>` | Default no-op |
Struct: CompactFormatter
A zero-state struct implementing `Formatter` that produces compact JSON output without added whitespace or indentation.
Implements all
Formattertrait methods with default behavior (no additional formatting).Suitable for minimal size serialization.
**Usage example:**
let mut formatter = CompactFormatter;
let mut buffer = Vec::new();
formatter.begin_object(&mut buffer)?;
formatter.begin_object_key(&mut buffer, true)?;
formatter.write_bool(&mut buffer, true)?;
formatter.end_object(&mut buffer)?;
Struct: PrettyFormatter
A stateful formatter implementing `Formatter` that produces pretty-printed JSON output with indentation and line breaks for readability.
Fields
Field | Type | Description |
|---|---|---|
`current_indent` | `usize` | Tracks the current indentation level (depth) |
`has_value` | `bool` | Indicates if the current container has any values |
Associated functions
new() -> Self: Constructs a newPrettyFormatterwith zero indentation and no values written.
Method behaviors (overrides)
Increases
current_indentwhen beginning arrays/objects.Decreases
current_indentwhen ending arrays/objects.Inserts line breaks and spaces proportional to
current_indent * 2.Writes commas and newlines between elements/keys.
Writes colon followed by space (
": ") between object keys and values.Tracks whether any values have been written to decide if newlines/spaces are needed before closing brackets/braces.
**Usage example:**
let mut formatter = PrettyFormatter::new();
let mut buffer = Vec::new();
formatter.begin_object(&mut buffer)?;
formatter.begin_object_key(&mut buffer, true)?;
formatter.write_bool(&mut buffer, true)?;
formatter.begin_object_key(&mut buffer, false)?;
formatter.write_i32(&mut buffer, 42)?;
formatter.end_object(&mut buffer)?;
This produces JSON like:
{
true,
42
}
(with proper indentation and line breaks).
Important Implementation Details
The formatter uses unsafe code to write directly into the writer's mutable buffer pointer for performance.
The macros
reserve_minimum!andreserve_pretty!(assumed defined elsewhere) ensure the writer has enough buffer capacity before writes.Number serialization uses efficient external crates:
itoapfor integer formatting (fast integer to ASCII conversion).ryufor floating point formatting (fast decimal float formatting).
The trait is designed for extensibility: new formatter implementations could override methods for different output styles or formats.
The
PrettyFormattermaintains internal state (current_indentandhas_value) to manage indentation and spacing, enabling human-readable output.
Interaction with Other System Components
This module depends on:
WriteExttrait fromcrate::serialize::writerwhich extends write functionality, probably wrapping or extending standardio::Write.bytes::BufMuttrait for efficient buffer mutation.External crates
itoapandryufor number formatting.
Likely used by a serializer component that converts Rust data structures into JSON by invoking these formatting methods sequentially.
The output writer
Wcan be any buffered writer, such as a memory buffer, file handle, or network stream.As an adaptation from
serde-json, it fits into a serialization framework compatible with Serde traits.
Visual Diagram
classDiagram
class Formatter {
<<trait>>
+write_null(writer)
+write_bool(writer, value)
+write_i32(writer, value)
+write_i64(writer, value)
+write_u32(writer, value)
+write_u64(writer, value)
+write_f32(writer, value)
+write_f64(writer, value)
+begin_array(writer)
+end_array(writer)
+begin_array_value(writer, first)
+end_array_value(writer)
+begin_object(writer)
+end_object(writer)
+begin_object_key(writer, first)
+end_object_key(writer)
+begin_object_value(writer)
+end_object_value(writer)
}
class CompactFormatter {
+Formatter
}
class PrettyFormatter {
-current_indent: usize
-has_value: bool
+new()
+Formatter
}
CompactFormatter ..|> Formatter
PrettyFormatter ..|> Formatter
Summary
`formatter.rs` provides a flexible and efficient framework for serializing data into JSON format. It defines a `Formatter` trait that abstracts the writing of JSON tokens and two implementations for compact and pretty output styles. It leverages low-level buffer manipulation and high-performance numeric formatting libraries. This module is essential in the serialization pipeline, enabling structured data to be represented as JSON text with configurable formatting.