json-schema-rs 0.0.3

A Rust library to generate Rust structs from JSON Schema.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
use crate::error::JsonSchemaGenError;
use crate::schema::JsonSchema;
use std::collections::BTreeMap;
use std::io::Write;

/// Represents a struct to be emitted, with its fields.
struct StructDef {
    name: String,
    fields: Vec<FieldDef>,
    deny_unknown_fields: bool,
}

/// Represents an enum to be emitted, with its variants (`rust_name`, `json_value`).
struct EnumDef {
    name: String,
    variants: Vec<(String, String)>,
}

/// Represents a field within a struct.
enum FieldDef {
    String {
        name: String,
        json_key: String,
        optional: bool,
    },
    Object {
        name: String,
        json_key: String,
        type_name: String,
        optional: bool,
    },
    Enum {
        name: String,
        json_key: String,
        type_name: String,
        optional: bool,
    },
    Boolean {
        name: String,
        json_key: String,
        optional: bool,
    },
    Array {
        name: String,
        json_key: String,
        element_type: String,
        optional: bool,
    },
    Integer {
        name: String,
        json_key: String,
        optional: bool,
    },
    Number {
        name: String,
        json_key: String,
        optional: bool,
    },
    AdditionalProperties {
        name: String,
        value_type: String,
    },
}

/// Convert a string to a valid Rust struct/type identifier (`PascalCase`).
/// Splits on any non-alphanumeric character (spaces, underscores, hyphens, etc.),
/// capitalizes each word, and joins with no separator.
/// Examples: `"The Widget_Settings Schema"` -> `"TheWidgetSettingsSchema"`, `"widget_settings"` -> `"WidgetSettings"`
fn to_rust_struct_name(s: &str) -> String {
    s.split(|c: char| !c.is_ascii_alphanumeric())
        .filter(|part| !part.is_empty())
        .map(|part| {
            let mut chars = part.chars();
            match chars.next() {
                None => String::new(),
                Some(first) => first.to_uppercase().chain(chars).collect(),
            }
        })
        .collect()
}

/// Sanitize a property key for use as a Rust field name (replace `-` with `_`).
fn sanitize_field_name(key: &str) -> String {
    key.replace('-', "_")
}

/// Generate a struct name from a property key and optional title.
fn struct_name_from_property(property_key: &str, title: Option<&str>) -> String {
    if let Some(t) = title {
        let trimmed: &str = t.trim();
        if !trimmed.is_empty() {
            return to_rust_struct_name(trimmed);
        }
    }
    to_rust_struct_name(property_key)
}

/// Convert a JSON enum value to a valid Rust enum variant identifier (`PascalCase`).
/// First char uppercase, rest lowercase per word. Prefixes with `E` (short for Enum)
/// if result is empty or starts with a digit.
fn to_rust_variant_name(s: &str) -> String {
    let base: String = s
        .split(|c: char| !c.is_ascii_alphanumeric())
        .filter(|part| !part.is_empty())
        .map(|part| {
            let mut chars: std::str::Chars<'_> = part.chars();
            match chars.next() {
                None => String::new(),
                Some(first) => first
                    .to_uppercase()
                    .chain(chars.flat_map(char::to_lowercase))
                    .collect(),
            }
        })
        .collect();
    if base.is_empty() || base.chars().next().is_some_and(|c| c.is_ascii_digit()) {
        format!("E{base}")
    } else {
        base
    }
}

/// Build enum variants from JSON Schema enum values: sort, deduplicate, handle collisions.
/// Returns `Vec<(rust_name, json_value)>`.
fn build_enum_variants(enum_values: &[String]) -> Vec<(String, String)> {
    // Deduplicate and sort for determinism
    let mut unique: Vec<String> = enum_values.to_vec();
    unique.sort();
    unique.dedup();

    // Group by base Rust name to detect collisions
    let base_names: Vec<String> = unique.iter().map(|s| to_rust_variant_name(s)).collect();
    let mut name_counts: std::collections::BTreeMap<String, usize> =
        std::collections::BTreeMap::new();
    for base in &base_names {
        *name_counts.entry(base.clone()).or_insert(0) += 1;
    }

    let mut result: Vec<(String, String)> = Vec::with_capacity(unique.len());
    let mut name_indices: std::collections::BTreeMap<String, usize> =
        std::collections::BTreeMap::new();

    for (json_val, base_name) in unique.iter().zip(base_names.iter()) {
        let rust_name: String = if *name_counts.get(base_name).unwrap_or(&0) > 1 {
            let idx: usize = *name_indices.get(base_name).unwrap_or(&0);
            name_indices.insert(base_name.clone(), idx + 1);
            format!("{base_name}_{idx}")
        } else {
            base_name.clone()
        };
        result.push((rust_name, json_val.clone()));
    }
    result
}

/// Resolve the Rust element type for an array's `items` schema.
/// Returns `None` if items type is unsupported or missing.
fn resolve_array_item_type(property_key: &str, items_schema: &JsonSchema) -> Option<String> {
    let item_type: &str = items_schema.r#type.as_deref().unwrap_or("");

    // Check for string enum first (same order as property handling)
    if let Some(ref enum_vals) = items_schema.r#enum {
        let string_values: Option<Vec<String>> = enum_vals
            .iter()
            .map(|v| v.as_str().map(String::from))
            .collect();
        if string_values.is_some() && !enum_vals.is_empty() {
            return Some(struct_name_from_property(
                property_key,
                items_schema.title.as_deref(),
            ));
        }
    }

    match item_type {
        "string" => Some("String".to_string()),
        "boolean" => Some("bool".to_string()),
        "integer" => Some("i64".to_string()),
        "number" => Some("f64".to_string()),
        "object" => Some(struct_name_from_property(
            property_key,
            items_schema.title.as_deref(),
        )),
        _ => None,
    }
}

/// Resolve the Rust value type for `additionalProperties` when it is a schema object.
/// Returns `None` if the value is not a schema object or is invalid.
/// For nested objects with properties, collects the struct into `collected`.
fn resolve_additional_properties_value_type(
    schema_value: &serde_json::Value,
    struct_name: &str,
    collected: &mut BTreeMap<String, StructDef>,
    collected_enums: &mut BTreeMap<String, EnumDef>,
) -> Option<String> {
    let ap_schema: JsonSchema = serde_json::from_value(schema_value.clone()).ok()?;
    let ap_type: &str = ap_schema.r#type.as_deref().unwrap_or("");

    if let Some(ref enum_vals) = ap_schema.r#enum {
        let string_values: Option<Vec<String>> = enum_vals
            .iter()
            .map(|v| v.as_str().map(String::from))
            .collect();
        if string_values.is_some() && !enum_vals.is_empty() {
            let enum_name: String = format!("{struct_name}Value");
            let vals: Vec<String> = enum_vals
                .iter()
                .filter_map(|v| v.as_str().map(String::from))
                .collect();
            let variants: Vec<(String, String)> = build_enum_variants(&vals);
            collected_enums.insert(
                enum_name.clone(),
                EnumDef {
                    name: enum_name.clone(),
                    variants,
                },
            );
            return Some(enum_name);
        }
    }

    match ap_type {
        "string" => Some("String".to_string()),
        "boolean" => Some("bool".to_string()),
        "integer" => Some("i64".to_string()),
        "number" => Some("f64".to_string()),
        "object" => {
            let nested_name: String = format!("{struct_name}Extra");
            if let Some(ref props) = ap_schema.properties
                && !props.is_empty()
            {
                collect_structs(&ap_schema, &nested_name, collected, collected_enums);
                return Some(nested_name);
            }
            Some("serde_json::Value".to_string())
        }
        _ => Some("serde_json::Value".to_string()),
    }
}

/// Recursively collect all structs and enums from a schema.
/// Uses `BTreeMap` for deterministic struct and field ordering (alphabetical by key).
#[expect(clippy::too_many_lines)]
fn collect_structs(
    schema: &JsonSchema,
    struct_name: &str,
    collected: &mut BTreeMap<String, StructDef>,
    collected_enums: &mut BTreeMap<String, EnumDef>,
) {
    let mut fields: Vec<FieldDef> = Vec::new();
    let deny_unknown_fields: bool = schema
        .additional_properties
        .as_ref()
        .and_then(serde_json::Value::as_bool)
        .is_some_and(|b| !b);

    if let Some(ref ap_value) = schema.additional_properties
        && ap_value.is_object()
        && let Some(value_type) = resolve_additional_properties_value_type(
            ap_value,
            struct_name,
            collected,
            collected_enums,
        )
    {
        fields.push(FieldDef::AdditionalProperties {
            name: "additional_properties".to_string(),
            value_type,
        });
    }

    if let Some(ref properties) = schema.properties {
        for (key, prop_schema) in properties {
            let prop_type = prop_schema.r#type.as_deref().unwrap_or("");
            let field_rust_name: String = sanitize_field_name(key);
            let is_required: bool = schema.required.as_ref().is_some_and(|r| r.contains(key));
            let optional: bool = !is_required;

            // Check for enum before type match
            if let Some(ref enum_vals) = prop_schema.r#enum {
                let string_values: Option<Vec<String>> = enum_vals
                    .iter()
                    .map(|v| v.as_str().map(String::from))
                    .collect();
                if let Some(vals) = string_values
                    && !vals.is_empty()
                {
                    let enum_name: String =
                        struct_name_from_property(key, prop_schema.title.as_deref());
                    let variants: Vec<(String, String)> = build_enum_variants(&vals);
                    collected_enums.insert(
                        enum_name.clone(),
                        EnumDef {
                            name: enum_name.clone(),
                            variants: variants.clone(),
                        },
                    );
                    fields.push(FieldDef::Enum {
                        name: field_rust_name.clone(),
                        json_key: key.clone(),
                        type_name: enum_name,
                        optional,
                    });
                    continue;
                }
            }

            match prop_type {
                "string" => {
                    fields.push(FieldDef::String {
                        name: field_rust_name.clone(),
                        json_key: key.clone(),
                        optional,
                    });
                }
                "boolean" => {
                    fields.push(FieldDef::Boolean {
                        name: field_rust_name.clone(),
                        json_key: key.clone(),
                        optional,
                    });
                }
                "integer" => {
                    fields.push(FieldDef::Integer {
                        name: field_rust_name.clone(),
                        json_key: key.clone(),
                        optional,
                    });
                }
                "number" => {
                    fields.push(FieldDef::Number {
                        name: field_rust_name.clone(),
                        json_key: key.clone(),
                        optional,
                    });
                }
                "object" => {
                    let nested_name: String =
                        struct_name_from_property(key, prop_schema.title.as_deref());
                    fields.push(FieldDef::Object {
                        name: field_rust_name.clone(),
                        json_key: key.clone(),
                        type_name: nested_name.clone(),
                        optional,
                    });
                    if let Some(ref nested_props) = prop_schema.properties
                        && !nested_props.is_empty()
                    {
                        collect_structs(prop_schema, &nested_name, collected, collected_enums);
                    }
                }
                "array" => {
                    let Some(ref items_schema) = prop_schema.items else {
                        continue;
                    };
                    let Some(element_type) = resolve_array_item_type(key, items_schema) else {
                        continue;
                    };
                    // Collect nested struct or enum for object/enum items
                    if items_schema.r#type.as_deref() == Some("object") {
                        if let Some(ref nested_props) = items_schema.properties
                            && !nested_props.is_empty()
                        {
                            collect_structs(
                                items_schema,
                                &element_type,
                                collected,
                                collected_enums,
                            );
                        }
                    } else if let Some(ref enum_vals) = items_schema.r#enum {
                        let string_values: Option<Vec<String>> = enum_vals
                            .iter()
                            .map(|v| v.as_str().map(String::from))
                            .collect();
                        if let Some(ref vals) = string_values
                            && !vals.is_empty()
                        {
                            let variants: Vec<(String, String)> = build_enum_variants(vals);
                            collected_enums.insert(
                                element_type.clone(),
                                EnumDef {
                                    name: element_type.clone(),
                                    variants,
                                },
                            );
                        }
                    }
                    fields.push(FieldDef::Array {
                        name: field_rust_name.clone(),
                        json_key: key.clone(),
                        element_type,
                        optional,
                    });
                }
                _ => {
                    // Ignore other types (null, etc.) for now
                }
            }
        }
    }

    if !fields.is_empty() || deny_unknown_fields {
        collected.insert(
            struct_name.to_string(),
            StructDef {
                name: struct_name.to_string(),
                fields,
                deny_unknown_fields,
            },
        );
    }
}

/// Escape a string for use inside a Rust double-quoted attribute.
fn escape_for_rust_attr(s: &str) -> String {
    s.replace('\\', "\\\\").replace('"', "\\\"")
}

/// Emit a single enum to the writer.
fn emit_enum<W: Write>(enum_def: &EnumDef, writer: &mut W) -> std::io::Result<()> {
    writeln!(
        writer,
        "#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]"
    )?;
    writeln!(writer, "pub enum {} {{", enum_def.name)?;
    for (rust_name, json_value) in &enum_def.variants {
        let escaped: String = escape_for_rust_attr(json_value);
        writeln!(writer, "    #[serde(rename = \"{escaped}\")]")?;
        writeln!(writer, "    {rust_name},")?;
    }
    writeln!(writer, "}}")?;
    writeln!(writer)?;
    Ok(())
}

/// Emit a single struct to the writer.
#[expect(clippy::too_many_lines)]
fn emit_struct<W: Write>(struct_def: &StructDef, writer: &mut W) -> std::io::Result<()> {
    writeln!(
        writer,
        "#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]"
    )?;
    if struct_def.deny_unknown_fields {
        writeln!(writer, "#[serde(deny_unknown_fields)]")?;
    }
    writeln!(writer, "pub struct {} {{", struct_def.name)?;
    for field in &struct_def.fields {
        match field {
            FieldDef::String {
                name,
                json_key,
                optional,
            } => {
                let type_str: &str = if *optional {
                    "Option<String>"
                } else {
                    "String"
                };
                if name == json_key {
                    writeln!(writer, "    pub {name}: {type_str},")?;
                } else {
                    writeln!(writer, "    #[serde(rename = \"{json_key}\")]")?;
                    writeln!(writer, "    pub {name}: {type_str},")?;
                }
            }
            FieldDef::Boolean {
                name,
                json_key,
                optional,
            } => {
                let type_str: &str = if *optional { "Option<bool>" } else { "bool" };
                if name == json_key {
                    writeln!(writer, "    pub {name}: {type_str},")?;
                } else {
                    writeln!(writer, "    #[serde(rename = \"{json_key}\")]")?;
                    writeln!(writer, "    pub {name}: {type_str},")?;
                }
            }
            FieldDef::Integer {
                name,
                json_key,
                optional,
            } => {
                let type_str: &str = if *optional { "Option<i64>" } else { "i64" };
                if name == json_key {
                    writeln!(writer, "    pub {name}: {type_str},")?;
                } else {
                    writeln!(writer, "    #[serde(rename = \"{json_key}\")]")?;
                    writeln!(writer, "    pub {name}: {type_str},")?;
                }
            }
            FieldDef::Number {
                name,
                json_key,
                optional,
            } => {
                let type_str: &str = if *optional { "Option<f64>" } else { "f64" };
                if name == json_key {
                    writeln!(writer, "    pub {name}: {type_str},")?;
                } else {
                    writeln!(writer, "    #[serde(rename = \"{json_key}\")]")?;
                    writeln!(writer, "    pub {name}: {type_str},")?;
                }
            }
            FieldDef::Object {
                name,
                json_key,
                type_name,
                optional,
            }
            | FieldDef::Enum {
                name,
                json_key,
                type_name,
                optional,
            } => {
                let type_str: String = if *optional {
                    format!("Option<{type_name}>")
                } else {
                    type_name.clone()
                };
                if name == json_key {
                    writeln!(writer, "    pub {name}: {type_str},")?;
                } else {
                    writeln!(writer, "    #[serde(rename = \"{json_key}\")]")?;
                    writeln!(writer, "    pub {name}: {type_str},")?;
                }
            }
            FieldDef::Array {
                name,
                json_key,
                element_type,
                optional,
            } => {
                let type_str: String = if *optional {
                    format!("Option<Vec<{element_type}>>")
                } else {
                    format!("Vec<{element_type}>")
                };
                if name == json_key {
                    writeln!(writer, "    pub {name}: {type_str},")?;
                } else {
                    writeln!(writer, "    #[serde(rename = \"{json_key}\")]")?;
                    writeln!(writer, "    pub {name}: {type_str},")?;
                }
            }
            FieldDef::AdditionalProperties { name, value_type } => {
                writeln!(writer, "    #[serde(flatten)]")?;
                writeln!(writer, "    pub {name}: BTreeMap<String, {value_type}>,")?;
            }
        }
    }
    writeln!(writer, "}}")?;
    writeln!(writer)?;
    Ok(())
}

/// Determine emission order: nested structs before their parents.
fn emission_order(struct_defs: &BTreeMap<String, StructDef>, root_name: &str) -> Vec<String> {
    fn visit(
        name: &str,
        struct_defs: &BTreeMap<String, StructDef>,
        order: &mut Vec<String>,
        visited: &mut std::collections::HashSet<String>,
    ) {
        if visited.contains(name) {
            return;
        }
        visited.insert(name.to_string());
        if let Some(def) = struct_defs.get(name) {
            for field in &def.fields {
                match field {
                    FieldDef::Object { type_name, .. } if struct_defs.contains_key(type_name) => {
                        visit(type_name, struct_defs, order, visited);
                    }
                    FieldDef::Array { element_type, .. }
                        if struct_defs.contains_key(element_type) =>
                    {
                        visit(element_type, struct_defs, order, visited);
                    }
                    FieldDef::AdditionalProperties { value_type, .. }
                        if struct_defs.contains_key(value_type) =>
                    {
                        visit(value_type, struct_defs, order, visited);
                    }
                    _ => {}
                }
            }
        }
        order.push(name.to_string());
    }

    let mut order: Vec<String> = Vec::new();
    let mut visited: std::collections::HashSet<String> = std::collections::HashSet::new();

    visit(root_name, struct_defs, &mut order, &mut visited);

    // Add any structs not reachable from root (shouldn't happen in our traversal, but be safe)
    for name in struct_defs.keys() {
        if !visited.contains(name) {
            visit(name, struct_defs, &mut order, &mut visited);
        }
    }

    order
}

/// Generate Rust structs from a JSON Schema string and write to `writer`.
pub fn generate_to_writer<W: Write>(
    schema_json: &str,
    writer: &mut W,
) -> Result<(), JsonSchemaGenError> {
    let schema: JsonSchema = serde_json::from_str(schema_json)?;

    let root_type: Option<&str> = schema.r#type.as_deref();
    if root_type != Some("object") {
        return Err(JsonSchemaGenError::GenericError(
            "Root schema must have type \"object\"".to_string(),
        ));
    }

    let root_name: String = schema
        .title
        .as_ref()
        .map(|t| to_rust_struct_name(t.trim()))
        .filter(|s| !s.is_empty())
        .unwrap_or_else(|| "Root".to_string());

    let mut collected: BTreeMap<String, StructDef> = BTreeMap::new();
    let mut collected_enums: BTreeMap<String, EnumDef> = BTreeMap::new();
    collect_structs(&schema, &root_name, &mut collected, &mut collected_enums);

    if collected.is_empty() {
        return Err(JsonSchemaGenError::GenericError(
            "No structs to generate (root object has no supported properties)".to_string(),
        ));
    }

    writeln!(
        writer,
        "//! Generated by json-schema-rs. Do not edit manually."
    )?;
    writeln!(writer)?;
    writeln!(writer, "use serde::{{Deserialize, Serialize}};")?;
    let needs_btreemap: bool = collected.values().any(|s| {
        s.fields
            .iter()
            .any(|f| matches!(f, FieldDef::AdditionalProperties { .. }))
    });
    if needs_btreemap {
        writeln!(writer, "use std::collections::BTreeMap;")?;
    }
    writeln!(writer)?;

    // Emit enums first (alphabetically), then structs (topological order)
    for enum_name in collected_enums.keys() {
        if let Some(enum_def) = collected_enums.get(enum_name) {
            emit_enum(enum_def, writer)?;
        }
    }
    let order: Vec<String> = emission_order(&collected, &root_name);
    for name in order {
        if let Some(struct_def) = collected.get(&name) {
            emit_struct(struct_def, writer)?;
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn to_rust_struct_name_sanitizes_spaces() {
        let actual: String = to_rust_struct_name("The Widget Schema");
        let expected: &str = "TheWidgetSchema";
        assert_eq!(expected, actual);
    }

    #[test]
    fn to_rust_struct_name_sanitizes_underscores_and_spaces() {
        let actual: String = to_rust_struct_name("The Foo_Bar Schema");
        let expected: &str = "TheFooBarSchema";
        assert_eq!(expected, actual);
    }

    #[test]
    fn to_rust_struct_name_snake_case_property_key() {
        let actual: String = to_rust_struct_name("widget");
        let expected: &str = "Widget";
        assert_eq!(expected, actual);
    }

    #[test]
    fn to_rust_struct_name_single_word() {
        let actual: String = to_rust_struct_name("Metadata");
        let expected: &str = "Metadata";
        assert_eq!(expected, actual);
    }

    #[test]
    fn to_rust_struct_name_with_hyphens() {
        let actual: String = to_rust_struct_name("foo-bar-baz");
        let expected: &str = "FooBarBaz";
        assert_eq!(expected, actual);
    }

    #[test]
    fn to_rust_variant_name_hyphenated() {
        let actual: String = to_rust_variant_name("blackjack-a");
        let expected: &str = "BlackjackA";
        assert_eq!(expected, actual);
    }

    #[test]
    fn to_rust_variant_name_numeric_prefix_gets_e_prefix() {
        let actual: String = to_rust_variant_name("123");
        let expected: &str = "E123";
        assert_eq!(expected, actual);
    }

    #[test]
    fn to_rust_variant_name_simple() {
        let actual: String = to_rust_variant_name("plain");
        let expected: &str = "Plain";
        assert_eq!(expected, actual);
    }

    #[test]
    fn to_rust_variant_name_uppercase() {
        let actual: String = to_rust_variant_name("PENDING");
        let expected: &str = "Pending";
        assert_eq!(expected, actual);
    }

    #[test]
    fn build_enum_variants_json_schema_duplicate_deduplicates() {
        let input: Vec<String> = vec!["a".to_string(), "a".to_string()];
        let actual: Vec<(String, String)> = build_enum_variants(&input);
        let expected: Vec<(String, String)> = vec![("A".to_string(), "a".to_string())];
        assert_eq!(
            expected, actual,
            "duplicate JSON enum values must deduplicate to one variant"
        );
    }

    #[test]
    fn build_enum_variants_rust_output_collision_disambiguates() {
        let input: Vec<String> = vec![
            "PENDING".to_string(),
            "pending".to_string(),
            "Pending".to_string(),
        ];
        let actual: Vec<(String, String)> = build_enum_variants(&input);
        let expected: Vec<(String, String)> = vec![
            ("Pending_0".to_string(), "PENDING".to_string()),
            ("Pending_1".to_string(), "Pending".to_string()),
            ("Pending_2".to_string(), "pending".to_string()),
        ];
        assert_eq!(
            expected, actual,
            "Rust variant name collision must produce Pending_0, Pending_1, Pending_2 with correct serde mapping"
        );
    }

    #[test]
    fn generate_schema_with_spaces_in_title_produces_valid_rust() {
        let schema_json: &str = r#"{
            "title": "WidgetFile",
            "type": "object",
            "properties": {
                "widget": {
                    "title": "The Widget Schema",
                    "type": "object",
                    "properties": {
                        "owner": { "type": "string" },
                        "name": { "type": "string" },
                        "version": { "type": "string" }
                    }
                }
            }
        }"#;

        let expected: &str = r"//! Generated by json-schema-rs. Do not edit manually.

use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TheWidgetSchema {
    pub name: Option<String>,
    pub owner: Option<String>,
    pub version: Option<String>,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct WidgetFile {
    pub widget: Option<TheWidgetSchema>,
}

";

        let mut output: Vec<u8> = Vec::new();
        generate_to_writer(schema_json, &mut output).expect("generate_to_writer should succeed");

        let actual: String = String::from_utf8(output).expect("output should be valid UTF-8");

        assert_eq!(expected, actual, "expected output to match exactly");
    }

    #[test]
    fn generate_schema_required_fields_emit_non_option() {
        let schema_json: &str = r#"{
            "type": "object",
            "title": "RequiredOnly",
            "required": ["x"],
            "properties": {
                "x": { "type": "string" }
            }
        }"#;

        let expected: &str = r"//! Generated by json-schema-rs. Do not edit manually.

use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RequiredOnly {
    pub x: String,
}

";

        let mut output: Vec<u8> = Vec::new();
        generate_to_writer(schema_json, &mut output).expect("generate_to_writer should succeed");

        let actual: String = String::from_utf8(output).expect("output should be valid UTF-8");

        assert_eq!(expected, actual, "expected output to match exactly");
    }

    #[test]
    fn generate_schema_optional_fields_emit_option() {
        let schema_json: &str = r#"{
            "type": "object",
            "title": "OptionalOnly",
            "properties": {
                "x": { "type": "string" }
            }
        }"#;

        let expected: &str = r"//! Generated by json-schema-rs. Do not edit manually.

use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct OptionalOnly {
    pub x: Option<String>,
}

";

        let mut output: Vec<u8> = Vec::new();
        generate_to_writer(schema_json, &mut output).expect("generate_to_writer should succeed");

        let actual: String = String::from_utf8(output).expect("output should be valid UTF-8");

        assert_eq!(expected, actual, "expected output to match exactly");
    }

    #[test]
    fn generate_schema_mixed_required_optional() {
        let schema_json: &str = r#"{
            "type": "object",
            "title": "Mixed",
            "required": ["req"],
            "properties": {
                "opt": { "type": "string" },
                "req": { "type": "string" }
            }
        }"#;

        let expected: &str = r"//! Generated by json-schema-rs. Do not edit manually.

use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Mixed {
    pub opt: Option<String>,
    pub req: String,
}

";

        let mut output: Vec<u8> = Vec::new();
        generate_to_writer(schema_json, &mut output).expect("generate_to_writer should succeed");

        let actual: String = String::from_utf8(output).expect("output should be valid UTF-8");

        assert_eq!(expected, actual, "expected output to match exactly");
    }

    #[test]
    fn generate_schema_empty_required_all_optional() {
        let schema_json: &str = r#"{
            "type": "object",
            "title": "EmptyRequired",
            "required": [],
            "properties": {
                "a": { "type": "string" },
                "b": { "type": "string" }
            }
        }"#;

        let expected: &str = r"//! Generated by json-schema-rs. Do not edit manually.

use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct EmptyRequired {
    pub a: Option<String>,
    pub b: Option<String>,
}

";

        let mut output: Vec<u8> = Vec::new();
        generate_to_writer(schema_json, &mut output).expect("generate_to_writer should succeed");

        let actual: String = String::from_utf8(output).expect("output should be valid UTF-8");

        assert_eq!(expected, actual, "expected output to match exactly");
    }
}