state.rs


Overview

`state.rs` defines the `SerializerState` struct, a compact and efficient representation of the internal state used during serialization operations. It encapsulates recursion and default call counts within a single 32-bit integer, allowing the serializer to track limits and manage nested or default serialization calls safely.

This file primarily provides mechanisms to:

These capabilities are critical to prevent infinite recursion or excessive default calls during serialization, which can occur in complex or cyclic data structures.


Detailed Explanation

Constants

These masks and shifts enable packing two 8-bit counters into a single `u32` while leaving the lower 16 bits for storing options.


Struct: SerializerState

#[repr(transparent)]
#[derive(Copy, Clone)]
pub(crate) struct SerializerState {
    state: u32,
}

Methods

new(opts: Opt) -> Self

Creates a new `SerializerState` initialized with the given options.

let opts = Opt::default(); // hypothetical Opt value
let state = SerializerState::new(opts);

opts(self) -> u32

Returns the raw options bits stored in `state`.

let options_bits = state.opts();

recursion_limit(self) -> bool

Checks if the recursion counter has reached its maximum value (`255`).

if state.recursion_limit() {
    // Handle recursion limit reached
}

default_calls_limit(self) -> bool

Checks if the default calls counter has reached its maximum value (`255`).

if state.default_calls_limit() {
    // Handle default calls limit reached
}

copy_for_recursive_call(self) -> Self

Produces a new `SerializerState` with the recursion counter incremented by 1.

let next_state = state.copy_for_recursive_call();

copy_for_default_call(self) -> Self

Produces a new `SerializerState` with the default calls counter incremented by 1.

let next_state = state.copy_for_default_call();

Important Implementation Details


Interaction with Other Parts of the System


Visual Diagram

classDiagram
    class SerializerState {
        -state: u32
        +new(opts: Opt) SerializerState
        +opts() u32
        +recursion_limit() bool
        +default_calls_limit() bool
        +copy_for_recursive_call() SerializerState
        +copy_for_default_call() SerializerState
    }

Summary

`state.rs` defines a compact `SerializerState` struct to manage serialization options and recursion/default call counters efficiently using bit manipulation. It provides methods to create new states, check limits, and produce incremented states for recursive or default serialization calls, aiding in controlling serialization flow and preventing overflow or infinite loops in complex data structures. This file is a foundational utility in the serialization subsystem, interacting closely with option definitions and the serialization logic.