Skip to content

Repository files navigation

Kilroy was here

Build StatusWindows Build StatusDocumentationCrate

PROST!

prost is a Protocol Buffers implementation for the Rust Language. prost generates simple, idiomatic Rust code from proto2 and proto3 files.

Compared to other Protocol Buffers implementations, prost

  • Generates simple, idiomatic, and readable Rust types by taking advantage of Rust derive attributes.
  • Retains comments from .proto files in generated Rust code.
  • Allows existing Rust types (not generated from a .proto) to be serialized and deserialized by adding attributes.
  • Uses the bytes::{Buf, BufMut} abstractions for serialization instead of std::io::{Read, Write}.
  • Respects the Protobuf package declaration when organizing generated code into Rust modules.
  • Preserves unknown enum values during deserialization.
  • Does not include support for runtime reflection or message descriptors.

Using prost in a Cargo Project

First, add prost and its public dependencies to your Cargo.toml (see crates.io for the current versions):

[dependencies]
prost = <prost-version>
prost-derive = <prost-version>
# Only necessary if using Protobuf well-known types:
prost-types = <prost-version>
bytes = <bytes-version>

The recommended way to add .proto compilation to a Cargo project is to use the prost-build library. See the prost-build documentation for more details and examples.

Generated Code

prost generates Rust code from source .proto files using the proto2 or proto3 syntax. prost's goal is to make the generated code as simple as possible.

Packages

Currently, all .proto files used with prost must contain a package declaration. prost will translate the Protobuf package into a Rust module. For example, given the package declaration:

packagefoo.bar;

All Rust types generated from the file will be in the foo::bar module.

Messages

Given a simple message declaration:

// Sample message.messageFoo {
}

prost will generate the following Rust struct:

/// Sample message.#[derive(Clone,Debug,PartialEq,Message)]pubstructFoo{}

Fields

Fields in Protobuf messages are translated into Rust as public struct fields of the corresponding type.

Scalar Values

Scalar value types are converted as follows:

Protobuf TypeRust Type
doublef64
floatf32
int32i32
int64i64
uint32u32
uint64u64
sint32i32
sint64i64
fixed32u32
fixed64u64
sfixed32i32
sfixed64i64
boolbool
stringString
bytesVec<u8>

Enumerations

All .proto enumeration types convert to the Rust i32 type. Additionally, each enumeration type gets a corresponding Rust enum type, with helper methods to convert i32 values to the enum type. The enum type isn't used directly as a field, because the Protobuf spec mandates that enumerations values are 'open', and decoding unrecognized enumeration values must be possible.

Field Modifiers

Protobuf scalar value and enumeration message fields can have a modifier depending on the Protobuf version. Modifiers change the corresponding type of the Rust field:

.proto VersionModifierRust Type
proto2optionalOption<T>
proto2requiredT
proto3defaultT
proto2/proto3repeatedVec<T>

Map Fields

Map fields are converted to a Rust HashMap with key and value type converted from the Protobuf key and value types.

Message Fields

Message fields are converted to the corresponding struct type. The table of field modifiers above applies to message fields, except that proto3 message fields without a modifier (the default) will be wrapped in an Option. Typically message fields are unboxed. prost will automatically box a message field if the field type and the parent type are recursively nested in order to avoid an infinite sized struct.

Oneof Fields

Oneof fields convert to a Rust enum. Protobuf oneofs types are not named, so prost uses the name of the oneof field for the resulting Rust enum, and defines the enum in a module under the struct. For example, a proto3 message such as:

messageFoo {
oneofwidget {
int32quux=1;
stringbar=2;
}
}

generates the following Rust[1]:

pubstructFoo{pubwidget:Option<foo::Widget>,}pubmod foo {pubenumWidget{Quux(i32),Bar(String),}}

oneof fields are always wrapped in an Option.

[1] Annotations have been elided for clarity. See below for a full example.

Services

prost-build allows a custom code-generator to be used for processing service definitions. This can be used to output Rust traits according to an application's specific needs.

Generated Code Example

Example .proto file:

syntax="proto3";
packagetutorial;
messagePerson {
stringname=1;
int32id=2; // Unique ID number for this person.stringemail=3;
enumPhoneType {
MOBILE=0;
HOME=1;
WORK=2;
}
messagePhoneNumber {
stringnumber=1;
PhoneTypetype=2;
}
repeatedPhoneNumberphones=4;
}
// Our address book file is just one of these.messageAddressBook {
repeatedPersonpeople=1;
}

and the generated Rust code (tutorial.rs):

#[derive(Clone,Debug,PartialEq,Message)]pubstructPerson{#[prost(string, tag="1")]pubname:String,/// Unique ID number for this person.#[prost(int32, tag="2")]pubid:i32,#[prost(string, tag="3")]pubemail:String,#[prost(message, repeated, tag="4")]pubphones:Vec<person::PhoneNumber>,}pubmod person {#[derive(Clone,Debug,PartialEq,Message)]pubstructPhoneNumber{#[prost(string, tag="1")]pubnumber:String,#[prost(enumeration="PhoneType", tag="2")]pubtype_:i32,}#[derive(Clone,Copy,Debug,PartialEq,Eq,Enumeration)]pubenumPhoneType{Mobile = 0,Home = 1,Work = 2,}}/// Our address book file is just one of these.#[derive(Clone,Debug,PartialEq,Message)]pubstructAddressBook{#[prost(message, repeated, tag="1")]pubpeople:Vec<Person>,}

Serializing Existing Types

prost uses a custom derive macro to handle encoding and decoding types, which means that if your existing Rust type is compatible with Protobuf types, you can serialize and deserialize it by adding the appropriate derive and field annotations.

Currently the best documentation on adding annotations is to look at the generated code examples above.

FAQ

  1. Could prost be implemented as a serializer for Serde?

Probably not, however I would like to hear from a Serde expert on the matter. There are two complications with trying to serialize Protobuf messages with Serde:

  • Protobuf fields require a numbered tag, and curently there appears to be no mechanism suitable for this in serde.
  • The mapping of Protobuf type to Rust type is not 1-to-1. As a result, trait-based approaches to dispatching don't work very well. Example: six different Protobuf field types correspond to a Rust Vec<i32>: repeated int32, repeated sint32, repeated sfixed32, and their packed counterparts.
  1. Looks like a lot of field annotations. Can those be simplified?

Probably. Effort has not yet been spent on reducing the number of annotations. The recommended way of using prost is through prost-build, in which case the annotations are never seen.

License

prost is distributed under the terms of the Apache License (Version 2.0).

See LICENSE for details.

Copyright 2017 Dan Burkert

About

PROST! a Protocol Buffers implementation for the Rust Language

Resources

Stars

0 stars

Watchers

13 watching

Forks

Releases

Packages

Contributors

Languages