#avro #code-generation #serde

bin+lib rsgen-avro

Command line and library for generating Rust types from Avro schemas

9 releases (5 breaking)

✓ Uses Rust 2018 edition

0.6.3 Jan 13, 2020
0.6.2 Jan 13, 2020
0.6.0 Dec 12, 2019
0.5.0 Jun 11, 2019
0.1.0 Oct 28, 2018

#134 in Encoding

Download history 39/week @ 2019-10-14 83/week @ 2019-10-21 61/week @ 2019-10-28 41/week @ 2019-11-04 60/week @ 2019-11-11 50/week @ 2019-11-18 58/week @ 2019-11-25 101/week @ 2019-12-02 94/week @ 2019-12-09 177/week @ 2019-12-16 54/week @ 2019-12-23 44/week @ 2019-12-30 37/week @ 2020-01-06 83/week @ 2020-01-13 51/week @ 2020-01-20

301 downloads per month

MIT license

64KB
1.5K SLoC

rsgen-avro

Crates.io Docs MIT licensed

A command line tool and library for generating serde-compatible Rust types from Avro schemas. The avro-rs crate provides a way to read and write Avro data with such types.

Command line usage

Install with:

cargo install rsgen-avro

Available options:

Usage:
  rsgen-avro [options] <schema-file-or-dir> <output-file>
  rsgen-avro (-h | --help)
  rsgen-avro (-V | --version)

Options:
  --fmt          Run rustfmt on the resulting <output-file>
  --nullable     Replace null fields with their default value
                 when deserializing.
  --precision=P  Precision for f32/f64 default values
                 that aren't round numbers [default: 3].
  -V, --version  Show version.
  -h, --help     Show this screen.

Library usage

As a libray, the basic usage is:

use rsgen_avro::{Source, Generator};

let raw_schema = r#"
{
    "type": "record",
    "name": "test",
    "fields": [
        {"name": "a", "type": "long", "default": 42},
        {"name": "b", "type": "string"}
    ]
}
"#;

let source = Source::SchemaStr(&raw_schema);

let mut out = std::io::stdout();

let g = Generator::new().unwrap();
g.gen(&source, &mut out).unwrap();

This will generate the following output:

use serde::{Deserialize, Serialize};

#[serde(default)]
#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
pub struct Test {
    pub a: i64,
    pub b: String,
}

impl Default for Test {
    fn default() -> Test {
        Test {
            a: 42,
            b: String::default(),
        }
    }
}

Various Schema sources can be used with Generator's .gen(..) method:

pub enum Source<'a> {
    Schema(&'a avro_rs::Schema), // from `avro-rs` crate
    SchemaStr(&'a str),
    FilePath(&'a std::path::Path),
    DirPath(&'a std::path::Path),
}

Note also that the Generator can be customized with a builder:

let g = Generator::builder().precision(2).build().unwrap();

Limitations

  • Avro schema namespace fields are ignored, therefore names from a single schema must no clash.
  • Only union of the form ["null", "some-type"] are supported and treated as Option<_>.

Dependencies

~8MB
~164K SLoC