Skip to content

Conversation

jonashao
Copy link

Description

This PR introduces integer type inference for Rust targets, providing better control over generated integer types (i32/i64):

  1. Added IntegerType enum with variants:

    • conservative: Selects i32/i64 based on JSON sample ranges
    • force-i32: Always uses i32 (caution: risk of overflow)
    • force-i64: Default behavior (current output)
  2. Added integerType configuration option for CLI and programmatic interfaces:

    quicktype --integer-type conservative  # Smart selection (default)
    quicktype --integer-type force-i32

Related Issue

#2790
(Original feature request: #2790)

Motivation and Context

  • ⚠️ Problem: Current behavior always generates i64 even when values fit in i32, causing:
    • Memory bloat (4-byte vs 8-byte overhead)
    • Compatibility issues with Rust libraries expecting i32
    • Serialization/deserialization performance penalties
  • Solution: Gives users control to optimize for:
    • Memory efficiency (force-i32)
    • Safety (force-i64)
    • Smart balancing (conservative)

Previous Behaviour / Output

All integers unconditionally became i64:

// JSON schema input:  {"id": {"type": "integer","minimum": 0, "maximum": 100}}
pub struct Data {
    pub id: i64,  // ← Always i64 even for small values
}

New Behaviour / Output

With --integer-type conservative:

// JSON schema input: {"id": {"type": "integer","minimum": 0, "maximum": 100}, "big": {"type": "integer","minimum": 0, "maximum": 9223372036854775807}}
pub struct Data {
    pub id: i32,   // ← conservative-downgraded to i32
    pub big: i64,  // ← Remains i64 for large values
}

How Has This Been Tested?

  1. Unit Tests:

    • Added integer-type.schema test input and rust langauge quickTestRendererOptions:
      • Range detection logic (conservative mode)
      • Forced type behaviors (force-i32/force-i64)
    • Integration tests for CLI flag parsing
  2. Validation Tests:

    # Tested with sample datasets:
    script/quicktype -s schema test/inputs/schema/integer-type.schema -o out.rs 
    script/quicktype -s schema test/inputs/schema/integer-type.schema -o out.rs  --integer-type force-i32
    script/quicktype -s schema test/inputs/schema/integer-type.schema -o out.rs  --integer-type force-i64
    • Verified output compiles with cargo check
  3. Environment:

    • Rust 1.87 + TypeScript 5.0
    • Windows/Linux/macOS cross-validation

1. Added IntegerType enum
2. Introduced integerType configuration option
 - Supports forced i32/i64 usage
 - Enables automatic selection based on numerical range
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant