Crate prost_build [−] [src]
prost-build
compiles .proto
files into Rust.
prost-build
is designed to be used for build-time code generation as part of a Cargo
build-script.
Example
Let's create a small crate, snazzy
, that defines a collection of
snazzy new items in a protobuf file.
$ cargo new snazzy && cd snazzy
First, add prost-build
, prost
and its public dependencies to Cargo.toml
(see crates.io for the current versions):
[dependencies]
bytes = <bytes-version>
prost = <prost-version>
prost-derive = <prost-version>
[build-dependencies]
prost-build = <prost-version>
Next, add src/items.proto
to the project:
syntax = "proto3";
package snazzy.items;
// A snazzy new shirt!
message Shirt {
enum Size {
SMALL = 0;
MEDIUM = 1;
LARGE = 2;
}
string color = 1;
Size size = 2;
}
To generate Rust code from items.proto
, we use prost-build
in the crate's
build.rs
build-script:
extern crate prost_build; fn main() { prost_build::compile_protos(&["src/items.proto"], &["src/"]).unwrap(); }
And finally, in lib.rs
, include the generated code:
extern crate prost; #[macro_use] extern crate prost_derive; // Include the `items` module, which is generated from items.proto. pub mod items { include!(concat!(env!("OUT_DIR"), "/snazzy.items.rs")); } pub fn create_large_shirt(color: String) -> items::Shirt { let mut shirt = items::Shirt::default(); shirt.color = color; shirt.set_size(items::shirt::Size::Large); shirt }
That's it! Run cargo doc
to see documentation for the generated code. The full
example project can be found on GitHub.
Sourcing protoc
prost-build
depends on the Protocol Buffers compiler, protoc
, to parse .proto
files into
a representation that can be transformed into Rust. If set, prost_build
will use the PROTOC
and PROTOC_INCLUDE
environment variables for locating protoc
and the protobuf built-in
includes. For example, on a macOS system where protobuf is installed with Homebrew, set the
environment to:
PROTOC=/usr/local/bin/protoc
PROTOC_INCLUDE=/usr/local/include
and in a typical Linux installation:
PROTOC=/usr/bin/protoc
PROTOC_INCLUDE=/usr/include
If PROTOC
and PROTOC_INCLUDE
are not found in the environment, then a pre-compiled protoc
binary embedded in the prost-build crate will be used. Pre-compiled protoc
binaries exist for
Linux, macOS, and Windows systems.
Structs
Comments |
Comments on a Protobuf item. |
Config |
Configuration options for Protobuf code generation. |
Method |
A service method descriptor. |
Service |
A service descriptor. |
Traits
ServiceGenerator |
A service generator takes a service descriptor and generates Rust code. |
Functions
compile_protos |
Compile |
protoc |
Returns the path to the |
protoc_include |
Returns the path to the Protobuf include directory. |