[][src]Crate flatc_rust

This crate provides a programmatical way to invoke flatc command (e.g. from build.rs) to generate Rust (or, in fact, any other language) helpers to work with FlatBuffers.

NOTE: You will still need flatc utility version 1.10.0+ installed (there are windows binary releases, flatbuffers packages for conda [Windows, Linux, MacOS], Arch Linux).

Examples

Minimal useful example

Let's assume you have input.fbs specification file in flatbuffers folder, and you want to generate Rust helpers into flatbuffers-helpers-for-rust folder:

use std::path::Path;

use flatc_rust;

flatc_rust::run(flatc_rust::Args {
    lang: "rust",  // `rust` is the default, but let's be explicit
    inputs: &[Path::new("./flatbuffers/input.fbs")],
    out_dir: Path::new("./flatbuffers-helpers-for-rust/"),
    ..Default::default()
})?;

Build scripts (build.rs) integration

It is common to have FlatBuffers specifications as a single source of truth, and thus, it is wise to build up-to-date helpers when you build your project. There is a built-in support for build scripts in Cargo, so you don't need to sacrifice the usual workflow (cargo build / cargo run) in order to generate the helpers.

  1. Create build.rs in the root of your project (along side with Cargo.toml) or follow the official documentation about build scripts.

  2. Adapt the following example to fit your needs and put it into build.rs:

    extern crate flatc_rust;  // or just `use flatc_rust;` with Rust 2018 edition.
    
    use std::path::Path;
    
    fn main() {
        println!("cargo:rerun-if-changed=src/message.fbs");
        flatc_rust::run(flatc_rust::Args {
            inputs: &[Path::new("src/message.fbs")],
            out_dir: Path::new("target/flatbuffers/"),
            ..Default::default()
        }).expect("flatc");
    }
  3. Add flatc-rust into [build-dependencies] section in Cargo.toml:

    [build-dependencies]
    flatc-rust = "*"
    
  4. Add flatbuffers into [dependencies] section in Cargo.toml:

    [dependencies]
    flatbuffers = "0.5"
    
  5. Include the generated helpers in your main.rs or lib.rs:

    This example is not tested
    #[allow(non_snake_case)]
    #[path = "../target/flatbuffers/message_generated.rs"]
    pub mod message_flatbuffers;
  6. Use the helpers like any regular Rust module (example projects)

Usage in external projects

There is a benchmark of FlatBuffers vs other serialization frameworks, which is based on flatc-rust integration.

Structs

Args

This structure represents the arguments passed to flatc

Flatc

Programmatic interface (API) for flatc command.

Version

FlatBuffers (flatc) version.

Functions

run

Execute flatc found in $PATH with given args

Type Definitions

Error

The default Error type of the crate

Result

The default Result type of the crate