| 1 |
 |
| 2 |
[](https://docs.rs/prost/) |
| 3 |
[](https://crates.io/crates/prost) |
| 4 |
[](https://deps.rs/repo/github/tokio-rs/prost) |
| 5 |
[](https://discord.gg/tokio) |
| 6 |
|
| 7 |
# *PROST!* |
| 8 |
|
| 9 |
`prost` is a [Protocol Buffers](https://developers.google.com/protocol-buffers/) |
| 10 |
implementation for the [Rust Language](https://www.rust-lang.org/). `prost` |
| 11 |
generates simple, idiomatic Rust code from `proto2` and `proto3` files. |
| 12 |
|
| 13 |
Compared to other Protocol Buffers implementations, `prost` |
| 14 |
|
| 15 |
* Generates simple, idiomatic, and readable Rust types by taking advantage of |
| 16 |
Rust `derive` attributes. |
| 17 |
* Retains comments from `.proto` files in generated Rust code. |
| 18 |
* Allows existing Rust types (not generated from a `.proto`) to be serialized |
| 19 |
and deserialized by adding attributes. |
| 20 |
* Uses the [`bytes::{Buf, BufMut}`](https://github.com/carllerche/bytes) |
| 21 |
abstractions for serialization instead of `std::io::{Read, Write}`. |
| 22 |
* Respects the Protobuf `package` specifier when organizing generated code |
| 23 |
into Rust modules. |
| 24 |
* Preserves unknown enum values during deserialization. |
| 25 |
* Does not include support for runtime reflection or message descriptors. |
| 26 |
|
| 27 |
## Using `prost` in a Cargo Project |
| 28 |
|
| 29 |
First, add `prost` and its public dependencies to your `Cargo.toml`: |
| 30 |
|
| 31 |
```ignore |
| 32 |
[dependencies] |
| 33 |
prost = "0.12" |
| 34 |
# Only necessary if using Protobuf well-known types: |
| 35 |
prost-types = "0.12" |
| 36 |
``` |
| 37 |
|
| 38 |
The recommended way to add `.proto` compilation to a Cargo project is to use the |
| 39 |
`prost-build` library. See the [`prost-build` documentation](prost-build) for |
| 40 |
more details and examples. |
| 41 |
|
| 42 |
See the [snazzy repository](https://github.com/danburkert/snazzy) for a simple |
| 43 |
start-to-finish example. |
| 44 |
|
| 45 |
### MSRV |
| 46 |
|
| 47 |
`prost` follows the `tokio-rs` projects MSRV model and supports 1.60. For more |
| 48 |
information on the tokio msrv policy you can check it out [here][tokio msrv] |
| 49 |
|
| 50 |
[tokio msrv]: https://github.com/tokio-rs/tokio/#supported-rust-versions |
| 51 |
|
| 52 |
## Generated Code |
| 53 |
|
| 54 |
`prost` generates Rust code from source `.proto` files using the `proto2` or |
| 55 |
`proto3` syntax. `prost`'s goal is to make the generated code as simple as |
| 56 |
possible. |
| 57 |
|
| 58 |
### `protoc` |
| 59 |
|
| 60 |
With `prost-build` v0.11 release, `protoc` will be required to invoke |
| 61 |
`compile_protos` (unless `skip_protoc` is enabled). Prost will no longer provide |
| 62 |
bundled a `protoc` or attempt to compile `protoc` for users. For install |
| 63 |
instructions for `protoc` please check out the [protobuf install] instructions. |
| 64 |
|
| 65 |
[protobuf install]: https://github.com/protocolbuffers/protobuf#protobuf-compiler-installation |
| 66 |
|
| 67 |
|
| 68 |
### Packages |
| 69 |
|
| 70 |
Prost can now generate code for `.proto` files that don't have a package spec. |
| 71 |
`prost` will translate the Protobuf package into |
| 72 |
a Rust module. For example, given the `package` specifier: |
| 73 |
|
| 74 |
[package]: https://developers.google.com/protocol-buffers/docs/proto#packages |
| 75 |
|
| 76 |
```protobuf,ignore |
| 77 |
package foo.bar; |
| 78 |
``` |
| 79 |
|
| 80 |
All Rust types generated from the file will be in the `foo::bar` module. |
| 81 |
|
| 82 |
### Messages |
| 83 |
|
| 84 |
Given a simple message declaration: |
| 85 |
|
| 86 |
```protobuf,ignore |
| 87 |
// Sample message. |
| 88 |
message Foo { |
| 89 |
} |
| 90 |
``` |
| 91 |
|
| 92 |
`prost` will generate the following Rust struct: |
| 93 |
|
| 94 |
```rust,ignore |
| 95 |
/// Sample message. |
| 96 |
#[derive(Clone, Debug, PartialEq, Message)] |
| 97 |
pub struct Foo { |
| 98 |
} |
| 99 |
``` |
| 100 |
|
| 101 |
### Fields |
| 102 |
|
| 103 |
Fields in Protobuf messages are translated into Rust as public struct fields of the |
| 104 |
corresponding type. |
| 105 |
|
| 106 |
#### Scalar Values |
| 107 |
|
| 108 |
Scalar value types are converted as follows: |
| 109 |
|
| 110 |
| Protobuf Type | Rust Type | |
| 111 |
| --- | --- | |
| 112 |
| `double` | `f64` | |
| 113 |
| `float` | `f32` | |
| 114 |
| `int32` | `i32` | |
| 115 |
| `int64` | `i64` | |
| 116 |
| `uint32` | `u32` | |
| 117 |
| `uint64` | `u64` | |
| 118 |
| `sint32` | `i32` | |
| 119 |
| `sint64` | `i64` | |
| 120 |
| `fixed32` | `u32` | |
| 121 |
| `fixed64` | `u64` | |
| 122 |
| `sfixed32` | `i32` | |
| 123 |
| `sfixed64` | `i64` | |
| 124 |
| `bool` | `bool` | |
| 125 |
| `string` | `String` | |
| 126 |
| `bytes` | `Vec<u8>` | |
| 127 |
|
| 128 |
#### Enumerations |
| 129 |
|
| 130 |
All `.proto` enumeration types convert to the Rust `i32` type. Additionally, |
| 131 |
each enumeration type gets a corresponding Rust `enum` type. For example, this |
| 132 |
`proto` enum: |
| 133 |
|
| 134 |
```protobuf,ignore |
| 135 |
enum PhoneType { |
| 136 |
MOBILE = 0; |
| 137 |
HOME = 1; |
| 138 |
WORK = 2; |
| 139 |
} |
| 140 |
``` |
| 141 |
|
| 142 |
gets this corresponding Rust enum [^1]: |
| 143 |
|
| 144 |
```rust,ignore |
| 145 |
pub enum PhoneType { |
| 146 |
Mobile = 0, |
| 147 |
Home = 1, |
| 148 |
Work = 2, |
| 149 |
} |
| 150 |
``` |
| 151 |
|
| 152 |
[^1]: Annotations have been elided for clarity. See below for a full example. |
| 153 |
|
| 154 |
You can convert a `PhoneType` value to an `i32` by doing: |
| 155 |
|
| 156 |
```rust,ignore |
| 157 |
PhoneType::Mobile as i32 |
| 158 |
``` |
| 159 |
|
| 160 |
The `#[derive(::prost::Enumeration)]` annotation added to the generated |
| 161 |
`PhoneType` adds these associated functions to the type: |
| 162 |
|
| 163 |
```rust,ignore |
| 164 |
impl PhoneType { |
| 165 |
pub fn is_valid(value: i32) -> bool { ... } |
| 166 |
#[deprecated] |
| 167 |
pub fn from_i32(value: i32) -> Option<PhoneType> { ... } |
| 168 |
} |
| 169 |
``` |
| 170 |
|
| 171 |
It also adds an `impl TryFrom<i32> for PhoneType`, so you can convert an `i32` to its corresponding `PhoneType` value by doing, |
| 172 |
for example: |
| 173 |
|
| 174 |
```rust,ignore |
| 175 |
let phone_type = 2i32; |
| 176 |
|
| 177 |
match PhoneType::try_from(phone_type) { |
| 178 |
Ok(PhoneType::Mobile) => ..., |
| 179 |
Ok(PhoneType::Home) => ..., |
| 180 |
Ok(PhoneType::Work) => ..., |
| 181 |
Err(_) => ..., |
| 182 |
} |
| 183 |
``` |
| 184 |
|
| 185 |
Additionally, wherever a `proto` enum is used as a field in a `Message`, the |
| 186 |
message will have 'accessor' methods to get/set the value of the field as the |
| 187 |
Rust enum type. For instance, this proto `PhoneNumber` message that has a field |
| 188 |
named `type` of type `PhoneType`: |
| 189 |
|
| 190 |
```protobuf,ignore |
| 191 |
message PhoneNumber { |
| 192 |
string number = 1; |
| 193 |
PhoneType type = 2; |
| 194 |
} |
| 195 |
``` |
| 196 |
|
| 197 |
will become the following Rust type [^2] with methods `type` and `set_type`: |
| 198 |
|
| 199 |
```rust,ignore |
| 200 |
pub struct PhoneNumber { |
| 201 |
pub number: String, |
| 202 |
pub r#type: i32, // the `r#` is needed because `type` is a Rust keyword |
| 203 |
} |
| 204 |
|
| 205 |
impl PhoneNumber { |
| 206 |
pub fn r#type(&self) -> PhoneType { ... } |
| 207 |
pub fn set_type(&mut self, value: PhoneType) { ... } |
| 208 |
} |
| 209 |
``` |
| 210 |
|
| 211 |
Note that the getter methods will return the Rust enum's default value if the |
| 212 |
field has an invalid `i32` value. |
| 213 |
|
| 214 |
The `enum` type isn't used directly as a field, because the Protobuf spec |
| 215 |
mandates that enumerations values are 'open', and decoding unrecognized |
| 216 |
enumeration values must be possible. |
| 217 |
|
| 218 |
[^2]: Annotations have been elided for clarity. See below for a full example. |
| 219 |
|
| 220 |
#### Field Modifiers |
| 221 |
|
| 222 |
Protobuf scalar value and enumeration message fields can have a modifier |
| 223 |
depending on the Protobuf version. Modifiers change the corresponding type of |
| 224 |
the Rust field: |
| 225 |
|
| 226 |
| `.proto` Version | Modifier | Rust Type | |
| 227 |
| --- | --- | --- | |
| 228 |
| `proto2` | `optional` | `Option<T>` | |
| 229 |
| `proto2` | `required` | `T` | |
| 230 |
| `proto3` | default | `T` for scalar types, `Option<T>` otherwise | |
| 231 |
| `proto3` | `optional` | `Option<T>` | |
| 232 |
| `proto2`/`proto3` | `repeated` | `Vec<T>` | |
| 233 |
|
| 234 |
Note that in `proto3` the default representation for all user-defined message |
| 235 |
types is `Option<T>`, and for scalar types just `T` (during decoding, a missing |
| 236 |
value is populated by `T::default()`). If you need a witness of the presence of |
| 237 |
a scalar type `T`, use the `optional` modifier to enforce an `Option<T>` |
| 238 |
representation in the generated Rust struct. |
| 239 |
|
| 240 |
#### Map Fields |
| 241 |
|
| 242 |
Map fields are converted to a Rust `HashMap` with key and value type converted |
| 243 |
from the Protobuf key and value types. |
| 244 |
|
| 245 |
#### Message Fields |
| 246 |
|
| 247 |
Message fields are converted to the corresponding struct type. The table of |
| 248 |
field modifiers above applies to message fields, except that `proto3` message |
| 249 |
fields without a modifier (the default) will be wrapped in an `Option`. |
| 250 |
Typically message fields are unboxed. `prost` will automatically box a message |
| 251 |
field if the field type and the parent type are recursively nested in order to |
| 252 |
avoid an infinite sized struct. |
| 253 |
|
| 254 |
#### Oneof Fields |
| 255 |
|
| 256 |
Oneof fields convert to a Rust enum. Protobuf `oneof`s types are not named, so |
| 257 |
`prost` uses the name of the `oneof` field for the resulting Rust enum, and |
| 258 |
defines the enum in a module under the struct. For example, a `proto3` message |
| 259 |
such as: |
| 260 |
|
| 261 |
```protobuf,ignore |
| 262 |
message Foo { |
| 263 |
oneof widget { |
| 264 |
int32 quux = 1; |
| 265 |
string bar = 2; |
| 266 |
} |
| 267 |
} |
| 268 |
``` |
| 269 |
|
| 270 |
generates the following Rust[^3]: |
| 271 |
|
| 272 |
```rust,ignore |
| 273 |
pub struct Foo { |
| 274 |
pub widget: Option<foo::Widget>, |
| 275 |
} |
| 276 |
pub mod foo { |
| 277 |
pub enum Widget { |
| 278 |
Quux(i32), |
| 279 |
Bar(String), |
| 280 |
} |
| 281 |
} |
| 282 |
``` |
| 283 |
|
| 284 |
`oneof` fields are always wrapped in an `Option`. |
| 285 |
|
| 286 |
[^3]: Annotations have been elided for clarity. See below for a full example. |
| 287 |
|
| 288 |
### Services |
| 289 |
|
| 290 |
`prost-build` allows a custom code-generator to be used for processing `service` |
| 291 |
definitions. This can be used to output Rust traits according to an |
| 292 |
application's specific needs. |
| 293 |
|
| 294 |
### Generated Code Example |
| 295 |
|
| 296 |
Example `.proto` file: |
| 297 |
|
| 298 |
```protobuf,ignore |
| 299 |
syntax = "proto3"; |
| 300 |
package tutorial; |
| 301 |
|
| 302 |
message Person { |
| 303 |
string name = 1; |
| 304 |
int32 id = 2; // Unique ID number for this person. |
| 305 |
string email = 3; |
| 306 |
|
| 307 |
enum PhoneType { |
| 308 |
MOBILE = 0; |
| 309 |
HOME = 1; |
| 310 |
WORK = 2; |
| 311 |
} |
| 312 |
|
| 313 |
message PhoneNumber { |
| 314 |
string number = 1; |
| 315 |
PhoneType type = 2; |
| 316 |
} |
| 317 |
|
| 318 |
repeated PhoneNumber phones = 4; |
| 319 |
} |
| 320 |
|
| 321 |
// Our address book file is just one of these. |
| 322 |
message AddressBook { |
| 323 |
repeated Person people = 1; |
| 324 |
} |
| 325 |
``` |
| 326 |
|
| 327 |
and the generated Rust code (`tutorial.rs`): |
| 328 |
|
| 329 |
```rust,ignore |
| 330 |
#[derive(Clone, PartialEq, ::prost::Message)] |
| 331 |
pub struct Person { |
| 332 |
#[prost(string, tag="1")] |
| 333 |
pub name: ::prost::alloc::string::String, |
| 334 |
/// Unique ID number for this person. |
| 335 |
#[prost(int32, tag="2")] |
| 336 |
pub id: i32, |
| 337 |
#[prost(string, tag="3")] |
| 338 |
pub email: ::prost::alloc::string::String, |
| 339 |
#[prost(message, repeated, tag="4")] |
| 340 |
pub phones: ::prost::alloc::vec::Vec<person::PhoneNumber>, |
| 341 |
} |
| 342 |
/// Nested message and enum types in `Person`. |
| 343 |
pub mod person { |
| 344 |
#[derive(Clone, PartialEq, ::prost::Message)] |
| 345 |
pub struct PhoneNumber { |
| 346 |
#[prost(string, tag="1")] |
| 347 |
pub number: ::prost::alloc::string::String, |
| 348 |
#[prost(enumeration="PhoneType", tag="2")] |
| 349 |
pub r#type: i32, |
| 350 |
} |
| 351 |
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] |
| 352 |
#[repr(i32)] |
| 353 |
pub enum PhoneType { |
| 354 |
Mobile = 0, |
| 355 |
Home = 1, |
| 356 |
Work = 2, |
| 357 |
} |
| 358 |
} |
| 359 |
/// Our address book file is just one of these. |
| 360 |
#[derive(Clone, PartialEq, ::prost::Message)] |
| 361 |
pub struct AddressBook { |
| 362 |
#[prost(message, repeated, tag="1")] |
| 363 |
pub people: ::prost::alloc::vec::Vec<Person>, |
| 364 |
} |
| 365 |
``` |
| 366 |
|
| 367 |
## Accessing the `protoc` `FileDescriptorSet` |
| 368 |
|
| 369 |
The `prost_build::Config::file_descriptor_set_path` option can be used to emit a file descriptor set |
| 370 |
during the build & code generation step. When used in conjunction with the `std::include_bytes` |
| 371 |
macro and the `prost_types::FileDescriptorSet` type, applications and libraries using Prost can |
| 372 |
implement introspection capabilities requiring details from the original `.proto` files. |
| 373 |
|
| 374 |
## Using `prost` in a `no_std` Crate |
| 375 |
|
| 376 |
`prost` is compatible with `no_std` crates. To enable `no_std` support, disable |
| 377 |
the `std` features in `prost` and `prost-types`: |
| 378 |
|
| 379 |
```ignore |
| 380 |
[dependencies] |
| 381 |
prost = { version = "0.6", default-features = false, features = ["prost-derive"] } |
| 382 |
# Only necessary if using Protobuf well-known types: |
| 383 |
prost-types = { version = "0.6", default-features = false } |
| 384 |
``` |
| 385 |
|
| 386 |
Additionally, configure `prost-build` to output `BTreeMap`s instead of `HashMap`s |
| 387 |
for all Protobuf `map` fields in your `build.rs`: |
| 388 |
|
| 389 |
```rust,ignore |
| 390 |
let mut config = prost_build::Config::new(); |
| 391 |
config.btree_map(&["."]); |
| 392 |
``` |
| 393 |
|
| 394 |
When using edition 2015, it may be necessary to add an `extern crate core;` |
| 395 |
directive to the crate which includes `prost`-generated code. |
| 396 |
|
| 397 |
## Serializing Existing Types |
| 398 |
|
| 399 |
`prost` uses a custom derive macro to handle encoding and decoding types, which |
| 400 |
means that if your existing Rust type is compatible with Protobuf types, you can |
| 401 |
serialize and deserialize it by adding the appropriate derive and field |
| 402 |
annotations. |
| 403 |
|
| 404 |
Currently the best documentation on adding annotations is to look at the |
| 405 |
generated code examples above. |
| 406 |
|
| 407 |
### Tag Inference for Existing Types |
| 408 |
|
| 409 |
Prost automatically infers tags for the struct. |
| 410 |
|
| 411 |
Fields are tagged sequentially in the order they |
| 412 |
are specified, starting with `1`. |
| 413 |
|
| 414 |
You may skip tags which have been reserved, or where there are gaps between |
| 415 |
sequentially occurring tag values by specifying the tag number to skip to with |
| 416 |
the `tag` attribute on the first field after the gap. The following fields will |
| 417 |
be tagged sequentially starting from the next number. |
| 418 |
|
| 419 |
```rust,ignore |
| 420 |
use prost; |
| 421 |
use prost::{Enumeration, Message}; |
| 422 |
|
| 423 |
#[derive(Clone, PartialEq, Message)] |
| 424 |
struct Person { |
| 425 |
#[prost(string, tag = "1")] |
| 426 |
pub id: String, // tag=1 |
| 427 |
// NOTE: Old "name" field has been removed |
| 428 |
// pub name: String, // tag=2 (Removed) |
| 429 |
#[prost(string, tag = "6")] |
| 430 |
pub given_name: String, // tag=6 |
| 431 |
#[prost(string)] |
| 432 |
pub family_name: String, // tag=7 |
| 433 |
#[prost(string)] |
| 434 |
pub formatted_name: String, // tag=8 |
| 435 |
#[prost(uint32, tag = "3")] |
| 436 |
pub age: u32, // tag=3 |
| 437 |
#[prost(uint32)] |
| 438 |
pub height: u32, // tag=4 |
| 439 |
#[prost(enumeration = "Gender")] |
| 440 |
pub gender: i32, // tag=5 |
| 441 |
// NOTE: Skip to less commonly occurring fields |
| 442 |
#[prost(string, tag = "16")] |
| 443 |
pub name_prefix: String, // tag=16 (eg. mr/mrs/ms) |
| 444 |
#[prost(string)] |
| 445 |
pub name_suffix: String, // tag=17 (eg. jr/esq) |
| 446 |
#[prost(string)] |
| 447 |
pub maiden_name: String, // tag=18 |
| 448 |
} |
| 449 |
|
| 450 |
#[derive(Clone, Copy, Debug, PartialEq, Eq, Enumeration)] |
| 451 |
pub enum Gender { |
| 452 |
Unknown = 0, |
| 453 |
Female = 1, |
| 454 |
Male = 2, |
| 455 |
} |
| 456 |
``` |
| 457 |
|
| 458 |
## Nix |
| 459 |
|
| 460 |
The prost project maintains flakes support for local development. Once you have |
| 461 |
nix and nix flakes setup you can just run `nix develop` to get a shell |
| 462 |
configured with the required dependencies to compile the whole project. |
| 463 |
|
| 464 |
|
| 465 |
## FAQ |
| 466 |
|
| 467 |
1. **Could `prost` be implemented as a serializer for [Serde](https://serde.rs/)?** |
| 468 |
|
| 469 |
Probably not, however I would like to hear from a Serde expert on the matter. |
| 470 |
There are two complications with trying to serialize Protobuf messages with |
| 471 |
Serde: |
| 472 |
|
| 473 |
- Protobuf fields require a numbered tag, and currently there appears to be no |
| 474 |
mechanism suitable for this in `serde`. |
| 475 |
- The mapping of Protobuf type to Rust type is not 1-to-1. As a result, |
| 476 |
trait-based approaches to dispatching don't work very well. Example: six |
| 477 |
different Protobuf field types correspond to a Rust `Vec<i32>`: `repeated |
| 478 |
int32`, `repeated sint32`, `repeated sfixed32`, and their packed |
| 479 |
counterparts. |
| 480 |
|
| 481 |
But it is possible to place `serde` derive tags onto the generated types, so |
| 482 |
the same structure can support both `prost` and `Serde`. |
| 483 |
|
| 484 |
2. **I get errors when trying to run `cargo test` on MacOS** |
| 485 |
|
| 486 |
If the errors are about missing `autoreconf` or similar, you can probably fix |
| 487 |
them by running |
| 488 |
|
| 489 |
```ignore |
| 490 |
brew install automake |
| 491 |
brew install libtool |
| 492 |
``` |
| 493 |
|
| 494 |
## License |
| 495 |
|
| 496 |
`prost` is distributed under the terms of the Apache License (Version 2.0). |
| 497 |
|
| 498 |
See [LICENSE](https://github.com/tokio-rs/prost/blob/master/LICENSE) for details. |
| 499 |
|
| 500 |
Copyright 2022 Dan Burkert & Tokio Contributors |