Skip to content

[FEATURE]: Smart Integer Type Inference for Rust Target #2790

Open
@jonashao

Description

@jonashao

Context (Input, Language)

Input Format: JSON
Output Language: Rust

Description

Currently, quicktype always generates i64 for integer values in Rust, regardless of the actual range of JSON numbers. This leads to:

  1. Suboptimal memory usage when values fit in i32
  2. Integration friction with Rust libraries expecting i32
  3. Performance penalties due to unnecessary 64-bit operations

We request type inference that chooses between i32 and i64 based on actual data ranges.

Current Behaviour / Output

All JSON integers become i64 in generated Rust:

pub struct Example {
    // Even small values like 42 become i64
    pub small_value: i64,
    pub large_value: i64,
}

Proposed Behaviour / Output

Intelligent inference:

pub struct Example {
    pub small_value: i32,  // Auto-detected from sample data
    pub large_value: i64,
}

Solution

  1. Range analysis during inference:

    • Track min/max values for integer fields
    • Use i32 if all samples are in [-2147483648, 2147483647]
    • Maintain i64 for larger values
  2. New CLI option:

    --integer-type [conservative|force-i32|force-i64]
    • conservative: Auto-detect based on samples (default)
    • force-i32: Assume i32 for all integers (with overflow risk)
    • force-i64: Current behavior (all i64)
  3. Implementation points:

    • Extend IntegerType in Type.ts with range tracking
    • Modify Rust renderer in Rust.ts to use inferred ranges

Alternatives

  1. User annotations:

    • Requires manual input changes (less user-friendly)
  2. Always use i64:

    • Maintains status quo but ignores Rust's efficiency benefits
  3. External configuration files:

    • More complex than range-based auto-detection

Context

Critical for:

  • Memory-constrained systems (embedded Rust)
  • High-performance applications
  • Projects interfacing with i32-based libraries (e.g., graphics APIs)
  • Large datasets where 4-byte vs 8-byte differences compound

Addresses Rust's philosophy of zero-cost abstractions while maintaining safety through sample-based validation.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions