json_schema_rs/lib.rs
1//! Generate Rust structs from JSON Schema.
2
3mod codegen;
4mod error;
5mod schema;
6
7pub use error::JsonSchemaGenError;
8pub use schema::JsonSchema;
9
10use std::io::Write;
11use std::path::Path;
12
13/// Generate Rust structs from a JSON Schema string and write to `writer`.
14///
15/// The writer can be any type implementing `Write`, such as `File`, `Vec<u8>`, or
16/// `Cursor<Vec<u8>>`, enabling easy unit testing without file system interaction.
17///
18/// # Errors
19///
20/// Returns `JsonSchemaGenError` if the schema JSON is invalid, the root is not an object,
21/// or writing to the writer fails.
22pub fn generate_to_writer<W: Write>(
23 schema_json: &str,
24 writer: &mut W,
25) -> Result<(), JsonSchemaGenError> {
26 codegen::generate_to_writer(schema_json, writer)
27}
28
29/// Generate Rust structs from a JSON Schema file and write to an output file.
30///
31/// # Errors
32///
33/// Returns `JsonSchemaGenError` if reading the input file fails, the schema JSON is invalid,
34/// the root is not an object, or writing to the output file fails.
35pub fn generate_from_file(
36 input_path: impl AsRef<Path>,
37 output_path: impl AsRef<Path>,
38) -> Result<(), JsonSchemaGenError> {
39 let schema_json: String = std::fs::read_to_string(input_path)?;
40 let mut output_file: std::fs::File = std::fs::File::create(output_path)?;
41 generate_to_writer(&schema_json, &mut output_file)
42}