Skip to content

Repository files navigation

continuous integrationDocumentationCrateDependency Status

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 specifier 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:

[dependencies]
prost = "0.10"
# Only necessary if using Protobuf well-known types:
prost-types = "0.10"

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.

See the snazzy repository for a simple start-to-finish example.

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.

protoc

It's recommended to install protoc locally in your path to improve build times. Prost uses protoc to parse protobuf files and will attempt to compile protobuf from source requiring a C++ toolchain. For more info checkout the prost-build docs.

Packages

Prost can now generate code for .proto files that don't have a package spec. prost will translate the Protobuf package into a Rust module. For example, given the package specifier:

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. For example, this proto enum:

enumPhoneType {
MOBILE=0;
HOME=1;
WORK=2;
}

gets this corresponding Rust enum [1]:

pubenumPhoneType{Mobile = 0,Home = 1,Work = 2,}

You can convert a PhoneType value to an i32 by doing:

PhoneType::Mobileasi32

The #[derive(::prost::Enumeration)] annotation added to the generated PhoneType adds these associated functions to the type:

implPhoneType{pubfnis_valid(value:i32) -> bool{ ...}pubfnfrom_i32(value:i32) -> Option<PhoneType>{ ...}}

so you can convert an i32 to its corresponding PhoneType value by doing, for example:

let phone_type = 2i32;matchPhoneType::from_i32(phone_type){Some(PhoneType::Mobile) => ...,Some(PhoneType::Home) => ...,Some(PhoneType::Work) => ...,None => ...,}

Additionally, wherever a proto enum is used as a field in a Message, the message will have 'accessor' methods to get/set the value of the field as the Rust enum type. For instance, this proto PhoneNumber message that has a field named type of type PhoneType:

messagePhoneNumber {
stringnumber=1;
PhoneTypetype=2;
}

will become the following Rust type [1] with methods type and set_type:

pubstructPhoneNumber{pubnumber:String,pubr#type:i32,// the `r#` is needed because `type` is a Rust keyword}implPhoneNumber{pubfnr#type(&self) -> PhoneType{ ...}pubfnset_type(&mutself,value:PhoneType){ ...}}

Note that the getter methods will return the Rust enum's default value if the field has an invalid i32 value.

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.

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

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 for scalar types, Option<T> otherwise
proto3optionalOption<T>
proto2/proto3repeatedVec<T>

Note that in proto3 the default representation for all user-defined message types is Option<T>, and for scalar types just T (during decoding, a missing value is populated by T::default()). If you need a witness of the presence of a scalar type T, use the optional modifier to enforce an Option<T> representation in the generated Rust struct.

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,PartialEq,::prost::Message)]pubstructPerson{#[prost(string, tag="1")]pubname:::prost::alloc::string::String,/// Unique ID number for this person.#[prost(int32, tag="2")]pubid:i32,#[prost(string, tag="3")]pubemail:::prost::alloc::string::String,#[prost(message, repeated, tag="4")]pubphones:::prost::alloc::vec::Vec<person::PhoneNumber>,}/// Nested message and enum types in `Person`.pubmod person {#[derive(Clone,PartialEq,::prost::Message)]pubstructPhoneNumber{#[prost(string, tag="1")]pubnumber:::prost::alloc::string::String,#[prost(enumeration="PhoneType", tag="2")]pubr#type:i32,}#[derive(Clone,Copy,Debug,PartialEq,Eq,Hash,PartialOrd,Ord,::prost::Enumeration)]#[repr(i32)]pubenumPhoneType{Mobile = 0,Home = 1,Work = 2,}}/// Our address book file is just one of these.#[derive(Clone,PartialEq,::prost::Message)]pubstructAddressBook{#[prost(message, repeated, tag="1")]pubpeople:::prost::alloc::vec::Vec<Person>,}

Accessing the protocFileDescriptorSet

The prost_build::Config::file_descriptor_set_path option can be used to emit a file descriptor set during the build & code generation step. When used in conjunction with the std::include_bytes macro and the prost_types::FileDescriptorSet type, applications and libraries using Prost can implement introspection capabilities requiring details from the original .proto files.

Using prost in a no_std Crate

prost is compatible with no_std crates. To enable no_std support, disable the std features in prost and prost-types:

[dependencies]
prost = { version = "0.6", default-features = false, features = ["prost-derive"] }
# Only necessary if using Protobuf well-known types:
prost-types = { version = "0.6", default-features = false }

Additionally, configure prost-build to output BTreeMaps instead of HashMaps for all Protobuf map fields in your build.rs:

letmut config = prost_build::Config::new();
config.btree_map(&["."]);

When using edition 2015, it may be necessary to add an extern crate core; directive to the crate which includes prost-generated code.

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.

Tag Inference for Existing Types

Prost automatically infers tags for the struct.

Fields are tagged sequentially in the order they are specified, starting with 1.

You may skip tags which have been reserved, or where there are gaps between sequentially occurring tag values by specifying the tag number to skip to with the tag attribute on the first field after the gap. The following fields will be tagged sequentially starting from the next number.

use prost;use prost::{Enumeration,Message};#[derive(Clone,PartialEq,Message)]structPerson{#[prost(string, tag = "1")]pubid:String,// tag=1// NOTE: Old "name" field has been removed// pub name: String, // tag=2 (Removed)#[prost(string, tag = "6")]pubgiven_name:String,// tag=6#[prost(string)]pubfamily_name:String,// tag=7#[prost(string)]pubformatted_name:String,// tag=8#[prost(uint32, tag = "3")]pubage:u32,// tag=3#[prost(uint32)]pubheight:u32,// tag=4#[prost(enumeration = "Gender")]pubgender:i32,// tag=5// NOTE: Skip to less commonly occurring fields#[prost(string, tag = "16")]pubname_prefix:String,// tag=16 (eg. mr/mrs/ms)#[prost(string)]pubname_suffix:String,// tag=17 (eg. jr/esq)#[prost(string)]pubmaiden_name:String,// tag=18}#[derive(Clone,Copy,Debug,PartialEq,Eq,Enumeration)]pubenumGender{Unknown = 0,Female = 1,Male = 2,}

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 currently 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.

But it is possible to place serde derive tags onto the generated types, so the same structure can support both prost and Serde.

  1. I get errors when trying to run cargo test on MacOS

If the errors are about missing autoreconf or similar, you can probably fix them by running

brew install automake
brew install libtool

License

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

See LICENSE for details.

Copyright 2022 Dan Burkert & Tokio Contributors

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

6 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
GitHub - phoenix-dataplane/prost · GitHub
Skip to content

Repository files navigation

continuous integrationDocumentationCrateDependency Status

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 specifier 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:

[dependencies]
prost = "0.10"
# Only necessary if using Protobuf well-known types:
prost-types = "0.10"

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.

See the snazzy repository for a simple start-to-finish example.

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.

protoc

It's recommended to install protoc locally in your path to improve build times. Prost uses protoc to parse protobuf files and will attempt to compile protobuf from source requiring a C++ toolchain. For more info checkout the prost-build docs.

Packages

Prost can now generate code for .proto files that don't have a package spec. prost will translate the Protobuf package into a Rust module. For example, given the package specifier:

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. For example, this proto enum:

enumPhoneType {
MOBILE=0;
HOME=1;
WORK=2;
}

gets this corresponding Rust enum [1]:

pubenumPhoneType{Mobile = 0,Home = 1,Work = 2,}

You can convert a PhoneType value to an i32 by doing:

PhoneType::Mobileasi32

The #[derive(::prost::Enumeration)] annotation added to the generated PhoneType adds these associated functions to the type:

implPhoneType{pubfnis_valid(value:i32) -> bool{ ...}pubfnfrom_i32(value:i32) -> Option<PhoneType>{ ...}}

so you can convert an i32 to its corresponding PhoneType value by doing, for example:

let phone_type = 2i32;matchPhoneType::from_i32(phone_type){Some(PhoneType::Mobile) => ...,Some(PhoneType::Home) => ...,Some(PhoneType::Work) => ...,None => ...,}

Additionally, wherever a proto enum is used as a field in a Message, the message will have 'accessor' methods to get/set the value of the field as the Rust enum type. For instance, this proto PhoneNumber message that has a field named type of type PhoneType:

messagePhoneNumber {
stringnumber=1;
PhoneTypetype=2;
}

will become the following Rust type [1] with methods type and set_type:

pubstructPhoneNumber{pubnumber:String,pubr#type:i32,// the `r#` is needed because `type` is a Rust keyword}implPhoneNumber{pubfnr#type(&self) -> PhoneType{ ...}pubfnset_type(&mutself,value:PhoneType){ ...}}

Note that the getter methods will return the Rust enum's default value if the field has an invalid i32 value.

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.

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

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 for scalar types, Option<T> otherwise
proto3optionalOption<T>
proto2/proto3repeatedVec<T>

Note that in proto3 the default representation for all user-defined message types is Option<T>, and for scalar types just T (during decoding, a missing value is populated by T::default()). If you need a witness of the presence of a scalar type T, use the optional modifier to enforce an Option<T> representation in the generated Rust struct.

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,PartialEq,::prost::Message)]pubstructPerson{#[prost(string, tag="1")]pubname:::prost::alloc::string::String,/// Unique ID number for this person.#[prost(int32, tag="2")]pubid:i32,#[prost(string, tag="3")]pubemail:::prost::alloc::string::String,#[prost(message, repeated, tag="4")]pubphones:::prost::alloc::vec::Vec<person::PhoneNumber>,}/// Nested message and enum types in `Person`.pubmod person {#[derive(Clone,PartialEq,::prost::Message)]pubstructPhoneNumber{#[prost(string, tag="1")]pubnumber:::prost::alloc::string::String,#[prost(enumeration="PhoneType", tag="2")]pubr#type:i32,}#[derive(Clone,Copy,Debug,PartialEq,Eq,Hash,PartialOrd,Ord,::prost::Enumeration)]#[repr(i32)]pubenumPhoneType{Mobile = 0,Home = 1,Work = 2,}}/// Our address book file is just one of these.#[derive(Clone,PartialEq,::prost::Message)]pubstructAddressBook{#[prost(message, repeated, tag="1")]pubpeople:::prost::alloc::vec::Vec<Person>,}

Accessing the protocFileDescriptorSet

The prost_build::Config::file_descriptor_set_path option can be used to emit a file descriptor set during the build & code generation step. When used in conjunction with the std::include_bytes macro and the prost_types::FileDescriptorSet type, applications and libraries using Prost can implement introspection capabilities requiring details from the original .proto files.

Using prost in a no_std Crate

prost is compatible with no_std crates. To enable no_std support, disable the std features in prost and prost-types:

[dependencies]
prost = { version = "0.6", default-features = false, features = ["prost-derive"] }
# Only necessary if using Protobuf well-known types:
prost-types = { version = "0.6", default-features = false }

Additionally, configure prost-build to output BTreeMaps instead of HashMaps for all Protobuf map fields in your build.rs:

letmut config = prost_build::Config::new();
config.btree_map(&["."]);

When using edition 2015, it may be necessary to add an extern crate core; directive to the crate which includes prost-generated code.

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.

Tag Inference for Existing Types

Prost automatically infers tags for the struct.

Fields are tagged sequentially in the order they are specified, starting with 1.

You may skip tags which have been reserved, or where there are gaps between sequentially occurring tag values by specifying the tag number to skip to with the tag attribute on the first field after the gap. The following fields will be tagged sequentially starting from the next number.

use prost;use prost::{Enumeration,Message};#[derive(Clone,PartialEq,Message)]structPerson{#[prost(string, tag = "1")]pubid:String,// tag=1// NOTE: Old "name" field has been removed// pub name: String, // tag=2 (Removed)#[prost(string, tag = "6")]pubgiven_name:String,// tag=6#[prost(string)]pubfamily_name:String,// tag=7#[prost(string)]pubformatted_name:String,// tag=8#[prost(uint32, tag = "3")]pubage:u32,// tag=3#[prost(uint32)]pubheight:u32,// tag=4#[prost(enumeration = "Gender")]pubgender:i32,// tag=5// NOTE: Skip to less commonly occurring fields#[prost(string, tag = "16")]pubname_prefix:String,// tag=16 (eg. mr/mrs/ms)#[prost(string)]pubname_suffix:String,// tag=17 (eg. jr/esq)#[prost(string)]pubmaiden_name:String,// tag=18}#[derive(Clone,Copy,Debug,PartialEq,Eq,Enumeration)]pubenumGender{Unknown = 0,Female = 1,Male = 2,}

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 currently 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.

But it is possible to place serde derive tags onto the generated types, so the same structure can support both prost and Serde.

  1. I get errors when trying to run cargo test on MacOS

If the errors are about missing autoreconf or similar, you can probably fix them by running

brew install automake
brew install libtool

License

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

See LICENSE for details.

Copyright 2022 Dan Burkert & Tokio Contributors

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

6 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - phoenix-dataplane/prost · GitHub
Skip to content

Repository files navigation

continuous integrationDocumentationCrateDependency Status

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 specifier 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:

[dependencies]
prost = "0.10"
# Only necessary if using Protobuf well-known types:
prost-types = "0.10"

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.

See the snazzy repository for a simple start-to-finish example.

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.

protoc

It's recommended to install protoc locally in your path to improve build times. Prost uses protoc to parse protobuf files and will attempt to compile protobuf from source requiring a C++ toolchain. For more info checkout the prost-build docs.

Packages

Prost can now generate code for .proto files that don't have a package spec. prost will translate the Protobuf package into a Rust module. For example, given the package specifier:

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. For example, this proto enum:

enumPhoneType {
MOBILE=0;
HOME=1;
WORK=2;
}

gets this corresponding Rust enum [1]:

pubenumPhoneType{Mobile = 0,Home = 1,Work = 2,}

You can convert a PhoneType value to an i32 by doing:

PhoneType::Mobileasi32

The #[derive(::prost::Enumeration)] annotation added to the generated PhoneType adds these associated functions to the type:

implPhoneType{pubfnis_valid(value:i32) -> bool{ ...}pubfnfrom_i32(value:i32) -> Option<PhoneType>{ ...}}

so you can convert an i32 to its corresponding PhoneType value by doing, for example:

let phone_type = 2i32;matchPhoneType::from_i32(phone_type){Some(PhoneType::Mobile) => ...,Some(PhoneType::Home) => ...,Some(PhoneType::Work) => ...,None => ...,}

Additionally, wherever a proto enum is used as a field in a Message, the message will have 'accessor' methods to get/set the value of the field as the Rust enum type. For instance, this proto PhoneNumber message that has a field named type of type PhoneType:

messagePhoneNumber {
stringnumber=1;
PhoneTypetype=2;
}

will become the following Rust type [1] with methods type and set_type:

pubstructPhoneNumber{pubnumber:String,pubr#type:i32,// the `r#` is needed because `type` is a Rust keyword}implPhoneNumber{pubfnr#type(&self) -> PhoneType{ ...}pubfnset_type(&mutself,value:PhoneType){ ...}}

Note that the getter methods will return the Rust enum's default value if the field has an invalid i32 value.

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.

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

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 for scalar types, Option<T> otherwise
proto3optionalOption<T>
proto2/proto3repeatedVec<T>

Note that in proto3 the default representation for all user-defined message types is Option<T>, and for scalar types just T (during decoding, a missing value is populated by T::default()). If you need a witness of the presence of a scalar type T, use the optional modifier to enforce an Option<T> representation in the generated Rust struct.

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,PartialEq,::prost::Message)]pubstructPerson{#[prost(string, tag="1")]pubname:::prost::alloc::string::String,/// Unique ID number for this person.#[prost(int32, tag="2")]pubid:i32,#[prost(string, tag="3")]pubemail:::prost::alloc::string::String,#[prost(message, repeated, tag="4")]pubphones:::prost::alloc::vec::Vec<person::PhoneNumber>,}/// Nested message and enum types in `Person`.pubmod person {#[derive(Clone,PartialEq,::prost::Message)]pubstructPhoneNumber{#[prost(string, tag="1")]pubnumber:::prost::alloc::string::String,#[prost(enumeration="PhoneType", tag="2")]pubr#type:i32,}#[derive(Clone,Copy,Debug,PartialEq,Eq,Hash,PartialOrd,Ord,::prost::Enumeration)]#[repr(i32)]pubenumPhoneType{Mobile = 0,Home = 1,Work = 2,}}/// Our address book file is just one of these.#[derive(Clone,PartialEq,::prost::Message)]pubstructAddressBook{#[prost(message, repeated, tag="1")]pubpeople:::prost::alloc::vec::Vec<Person>,}

Accessing the protocFileDescriptorSet

The prost_build::Config::file_descriptor_set_path option can be used to emit a file descriptor set during the build & code generation step. When used in conjunction with the std::include_bytes macro and the prost_types::FileDescriptorSet type, applications and libraries using Prost can implement introspection capabilities requiring details from the original .proto files.

Using prost in a no_std Crate

prost is compatible with no_std crates. To enable no_std support, disable the std features in prost and prost-types:

[dependencies]
prost = { version = "0.6", default-features = false, features = ["prost-derive"] }
# Only necessary if using Protobuf well-known types:
prost-types = { version = "0.6", default-features = false }

Additionally, configure prost-build to output BTreeMaps instead of HashMaps for all Protobuf map fields in your build.rs:

letmut config = prost_build::Config::new();
config.btree_map(&["."]);

When using edition 2015, it may be necessary to add an extern crate core; directive to the crate which includes prost-generated code.

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.

Tag Inference for Existing Types

Prost automatically infers tags for the struct.

Fields are tagged sequentially in the order they are specified, starting with 1.

You may skip tags which have been reserved, or where there are gaps between sequentially occurring tag values by specifying the tag number to skip to with the tag attribute on the first field after the gap. The following fields will be tagged sequentially starting from the next number.

use prost;use prost::{Enumeration,Message};#[derive(Clone,PartialEq,Message)]structPerson{#[prost(string, tag = "1")]pubid:String,// tag=1// NOTE: Old "name" field has been removed// pub name: String, // tag=2 (Removed)#[prost(string, tag = "6")]pubgiven_name:String,// tag=6#[prost(string)]pubfamily_name:String,// tag=7#[prost(string)]pubformatted_name:String,// tag=8#[prost(uint32, tag = "3")]pubage:u32,// tag=3#[prost(uint32)]pubheight:u32,// tag=4#[prost(enumeration = "Gender")]pubgender:i32,// tag=5// NOTE: Skip to less commonly occurring fields#[prost(string, tag = "16")]pubname_prefix:String,// tag=16 (eg. mr/mrs/ms)#[prost(string)]pubname_suffix:String,// tag=17 (eg. jr/esq)#[prost(string)]pubmaiden_name:String,// tag=18}#[derive(Clone,Copy,Debug,PartialEq,Eq,Enumeration)]pubenumGender{Unknown = 0,Female = 1,Male = 2,}

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 currently 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.

But it is possible to place serde derive tags onto the generated types, so the same structure can support both prost and Serde.

  1. I get errors when trying to run cargo test on MacOS

If the errors are about missing autoreconf or similar, you can probably fix them by running

brew install automake
brew install libtool

License

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

See LICENSE for details.

Copyright 2022 Dan Burkert & Tokio Contributors

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

6 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - phoenix-dataplane/prost · GitHub
Skip to content

Repository files navigation

continuous integrationDocumentationCrateDependency Status

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 specifier 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:

[dependencies]
prost = "0.10"
# Only necessary if using Protobuf well-known types:
prost-types = "0.10"

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.

See the snazzy repository for a simple start-to-finish example.

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.

protoc

It's recommended to install protoc locally in your path to improve build times. Prost uses protoc to parse protobuf files and will attempt to compile protobuf from source requiring a C++ toolchain. For more info checkout the prost-build docs.

Packages

Prost can now generate code for .proto files that don't have a package spec. prost will translate the Protobuf package into a Rust module. For example, given the package specifier:

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. For example, this proto enum:

enumPhoneType {
MOBILE=0;
HOME=1;
WORK=2;
}

gets this corresponding Rust enum [1]:

pubenumPhoneType{Mobile = 0,Home = 1,Work = 2,}

You can convert a PhoneType value to an i32 by doing:

PhoneType::Mobileasi32

The #[derive(::prost::Enumeration)] annotation added to the generated PhoneType adds these associated functions to the type:

implPhoneType{pubfnis_valid(value:i32) -> bool{ ...}pubfnfrom_i32(value:i32) -> Option<PhoneType>{ ...}}

so you can convert an i32 to its corresponding PhoneType value by doing, for example:

let phone_type = 2i32;matchPhoneType::from_i32(phone_type){Some(PhoneType::Mobile) => ...,Some(PhoneType::Home) => ...,Some(PhoneType::Work) => ...,None => ...,}

Additionally, wherever a proto enum is used as a field in a Message, the message will have 'accessor' methods to get/set the value of the field as the Rust enum type. For instance, this proto PhoneNumber message that has a field named type of type PhoneType:

messagePhoneNumber {
stringnumber=1;
PhoneTypetype=2;
}

will become the following Rust type [1] with methods type and set_type:

pubstructPhoneNumber{pubnumber:String,pubr#type:i32,// the `r#` is needed because `type` is a Rust keyword}implPhoneNumber{pubfnr#type(&self) -> PhoneType{ ...}pubfnset_type(&mutself,value:PhoneType){ ...}}

Note that the getter methods will return the Rust enum's default value if the field has an invalid i32 value.

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.

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

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 for scalar types, Option<T> otherwise
proto3optionalOption<T>
proto2/proto3repeatedVec<T>

Note that in proto3 the default representation for all user-defined message types is Option<T>, and for scalar types just T (during decoding, a missing value is populated by T::default()). If you need a witness of the presence of a scalar type T, use the optional modifier to enforce an Option<T> representation in the generated Rust struct.

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,PartialEq,::prost::Message)]pubstructPerson{#[prost(string, tag="1")]pubname:::prost::alloc::string::String,/// Unique ID number for this person.#[prost(int32, tag="2")]pubid:i32,#[prost(string, tag="3")]pubemail:::prost::alloc::string::String,#[prost(message, repeated, tag="4")]pubphones:::prost::alloc::vec::Vec<person::PhoneNumber>,}/// Nested message and enum types in `Person`.pubmod person {#[derive(Clone,PartialEq,::prost::Message)]pubstructPhoneNumber{#[prost(string, tag="1")]pubnumber:::prost::alloc::string::String,#[prost(enumeration="PhoneType", tag="2")]pubr#type:i32,}#[derive(Clone,Copy,Debug,PartialEq,Eq,Hash,PartialOrd,Ord,::prost::Enumeration)]#[repr(i32)]pubenumPhoneType{Mobile = 0,Home = 1,Work = 2,}}/// Our address book file is just one of these.#[derive(Clone,PartialEq,::prost::Message)]pubstructAddressBook{#[prost(message, repeated, tag="1")]pubpeople:::prost::alloc::vec::Vec<Person>,}

Accessing the protocFileDescriptorSet

The prost_build::Config::file_descriptor_set_path option can be used to emit a file descriptor set during the build & code generation step. When used in conjunction with the std::include_bytes macro and the prost_types::FileDescriptorSet type, applications and libraries using Prost can implement introspection capabilities requiring details from the original .proto files.

Using prost in a no_std Crate

prost is compatible with no_std crates. To enable no_std support, disable the std features in prost and prost-types:

[dependencies]
prost = { version = "0.6", default-features = false, features = ["prost-derive"] }
# Only necessary if using Protobuf well-known types:
prost-types = { version = "0.6", default-features = false }

Additionally, configure prost-build to output BTreeMaps instead of HashMaps for all Protobuf map fields in your build.rs:

letmut config = prost_build::Config::new();
config.btree_map(&["."]);

When using edition 2015, it may be necessary to add an extern crate core; directive to the crate which includes prost-generated code.

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.

Tag Inference for Existing Types

Prost automatically infers tags for the struct.

Fields are tagged sequentially in the order they are specified, starting with 1.

You may skip tags which have been reserved, or where there are gaps between sequentially occurring tag values by specifying the tag number to skip to with the tag attribute on the first field after the gap. The following fields will be tagged sequentially starting from the next number.

use prost;use prost::{Enumeration,Message};#[derive(Clone,PartialEq,Message)]structPerson{#[prost(string, tag = "1")]pubid:String,// tag=1// NOTE: Old "name" field has been removed// pub name: String, // tag=2 (Removed)#[prost(string, tag = "6")]pubgiven_name:String,// tag=6#[prost(string)]pubfamily_name:String,// tag=7#[prost(string)]pubformatted_name:String,// tag=8#[prost(uint32, tag = "3")]pubage:u32,// tag=3#[prost(uint32)]pubheight:u32,// tag=4#[prost(enumeration = "Gender")]pubgender:i32,// tag=5// NOTE: Skip to less commonly occurring fields#[prost(string, tag = "16")]pubname_prefix:String,// tag=16 (eg. mr/mrs/ms)#[prost(string)]pubname_suffix:String,// tag=17 (eg. jr/esq)#[prost(string)]pubmaiden_name:String,// tag=18}#[derive(Clone,Copy,Debug,PartialEq,Eq,Enumeration)]pubenumGender{Unknown = 0,Female = 1,Male = 2,}

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 currently 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.

But it is possible to place serde derive tags onto the generated types, so the same structure can support both prost and Serde.

  1. I get errors when trying to run cargo test on MacOS

If the errors are about missing autoreconf or similar, you can probably fix them by running

brew install automake
brew install libtool

License

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

See LICENSE for details.

Copyright 2022 Dan Burkert & Tokio Contributors

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

6 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' GitHub - phoenix-dataplane/prost · GitHub
Skip to content

Repository files navigation

continuous integrationDocumentationCrateDependency Status

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 specifier 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:

[dependencies]
prost = "0.10"
# Only necessary if using Protobuf well-known types:
prost-types = "0.10"

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.

See the snazzy repository for a simple start-to-finish example.

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.

protoc

It's recommended to install protoc locally in your path to improve build times. Prost uses protoc to parse protobuf files and will attempt to compile protobuf from source requiring a C++ toolchain. For more info checkout the prost-build docs.

Packages

Prost can now generate code for .proto files that don't have a package spec. prost will translate the Protobuf package into a Rust module. For example, given the package specifier:

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. For example, this proto enum:

enumPhoneType {
MOBILE=0;
HOME=1;
WORK=2;
}

gets this corresponding Rust enum [1]:

pubenumPhoneType{Mobile = 0,Home = 1,Work = 2,}

You can convert a PhoneType value to an i32 by doing:

PhoneType::Mobileasi32

The #[derive(::prost::Enumeration)] annotation added to the generated PhoneType adds these associated functions to the type:

implPhoneType{pubfnis_valid(value:i32) -> bool{ ...}pubfnfrom_i32(value:i32) -> Option<PhoneType>{ ...}}

so you can convert an i32 to its corresponding PhoneType value by doing, for example:

let phone_type = 2i32;matchPhoneType::from_i32(phone_type){Some(PhoneType::Mobile) => ...,Some(PhoneType::Home) => ...,Some(PhoneType::Work) => ...,None => ...,}

Additionally, wherever a proto enum is used as a field in a Message, the message will have 'accessor' methods to get/set the value of the field as the Rust enum type. For instance, this proto PhoneNumber message that has a field named type of type PhoneType:

messagePhoneNumber {
stringnumber=1;
PhoneTypetype=2;
}

will become the following Rust type [1] with methods type and set_type:

pubstructPhoneNumber{pubnumber:String,pubr#type:i32,// the `r#` is needed because `type` is a Rust keyword}implPhoneNumber{pubfnr#type(&self) -> PhoneType{ ...}pubfnset_type(&mutself,value:PhoneType){ ...}}

Note that the getter methods will return the Rust enum's default value if the field has an invalid i32 value.

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.

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

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 for scalar types, Option<T> otherwise
proto3optionalOption<T>
proto2/proto3repeatedVec<T>

Note that in proto3 the default representation for all user-defined message types is Option<T>, and for scalar types just T (during decoding, a missing value is populated by T::default()). If you need a witness of the presence of a scalar type T, use the optional modifier to enforce an Option<T> representation in the generated Rust struct.

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,PartialEq,::prost::Message)]pubstructPerson{#[prost(string, tag="1")]pubname:::prost::alloc::string::String,/// Unique ID number for this person.#[prost(int32, tag="2")]pubid:i32,#[prost(string, tag="3")]pubemail:::prost::alloc::string::String,#[prost(message, repeated, tag="4")]pubphones:::prost::alloc::vec::Vec<person::PhoneNumber>,}/// Nested message and enum types in `Person`.pubmod person {#[derive(Clone,PartialEq,::prost::Message)]pubstructPhoneNumber{#[prost(string, tag="1")]pubnumber:::prost::alloc::string::String,#[prost(enumeration="PhoneType", tag="2")]pubr#type:i32,}#[derive(Clone,Copy,Debug,PartialEq,Eq,Hash,PartialOrd,Ord,::prost::Enumeration)]#[repr(i32)]pubenumPhoneType{Mobile = 0,Home = 1,Work = 2,}}/// Our address book file is just one of these.#[derive(Clone,PartialEq,::prost::Message)]pubstructAddressBook{#[prost(message, repeated, tag="1")]pubpeople:::prost::alloc::vec::Vec<Person>,}

Accessing the protocFileDescriptorSet

The prost_build::Config::file_descriptor_set_path option can be used to emit a file descriptor set during the build & code generation step. When used in conjunction with the std::include_bytes macro and the prost_types::FileDescriptorSet type, applications and libraries using Prost can implement introspection capabilities requiring details from the original .proto files.

Using prost in a no_std Crate

prost is compatible with no_std crates. To enable no_std support, disable the std features in prost and prost-types:

[dependencies]
prost = { version = "0.6", default-features = false, features = ["prost-derive"] }
# Only necessary if using Protobuf well-known types:
prost-types = { version = "0.6", default-features = false }

Additionally, configure prost-build to output BTreeMaps instead of HashMaps for all Protobuf map fields in your build.rs:

letmut config = prost_build::Config::new();
config.btree_map(&["."]);

When using edition 2015, it may be necessary to add an extern crate core; directive to the crate which includes prost-generated code.

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.

Tag Inference for Existing Types

Prost automatically infers tags for the struct.

Fields are tagged sequentially in the order they are specified, starting with 1.

You may skip tags which have been reserved, or where there are gaps between sequentially occurring tag values by specifying the tag number to skip to with the tag attribute on the first field after the gap. The following fields will be tagged sequentially starting from the next number.

use prost;use prost::{Enumeration,Message};#[derive(Clone,PartialEq,Message)]structPerson{#[prost(string, tag = "1")]pubid:String,// tag=1// NOTE: Old "name" field has been removed// pub name: String, // tag=2 (Removed)#[prost(string, tag = "6")]pubgiven_name:String,// tag=6#[prost(string)]pubfamily_name:String,// tag=7#[prost(string)]pubformatted_name:String,// tag=8#[prost(uint32, tag = "3")]pubage:u32,// tag=3#[prost(uint32)]pubheight:u32,// tag=4#[prost(enumeration = "Gender")]pubgender:i32,// tag=5// NOTE: Skip to less commonly occurring fields#[prost(string, tag = "16")]pubname_prefix:String,// tag=16 (eg. mr/mrs/ms)#[prost(string)]pubname_suffix:String,// tag=17 (eg. jr/esq)#[prost(string)]pubmaiden_name:String,// tag=18}#[derive(Clone,Copy,Debug,PartialEq,Eq,Enumeration)]pubenumGender{Unknown = 0,Female = 1,Male = 2,}

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 currently 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.

But it is possible to place serde derive tags onto the generated types, so the same structure can support both prost and Serde.

  1. I get errors when trying to run cargo test on MacOS

If the errors are about missing autoreconf or similar, you can probably fix them by running

brew install automake
brew install libtool

License

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

See LICENSE for details.

Copyright 2022 Dan Burkert & Tokio Contributors

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

6 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - phoenix-dataplane/prost · GitHub
Skip to content

Repository files navigation

continuous integrationDocumentationCrateDependency Status

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 specifier 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:

[dependencies]
prost = "0.10"
# Only necessary if using Protobuf well-known types:
prost-types = "0.10"

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.

See the snazzy repository for a simple start-to-finish example.

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.

protoc

It's recommended to install protoc locally in your path to improve build times. Prost uses protoc to parse protobuf files and will attempt to compile protobuf from source requiring a C++ toolchain. For more info checkout the prost-build docs.

Packages

Prost can now generate code for .proto files that don't have a package spec. prost will translate the Protobuf package into a Rust module. For example, given the package specifier:

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. For example, this proto enum:

enumPhoneType {
MOBILE=0;
HOME=1;
WORK=2;
}

gets this corresponding Rust enum [1]:

pubenumPhoneType{Mobile = 0,Home = 1,Work = 2,}

You can convert a PhoneType value to an i32 by doing:

PhoneType::Mobileasi32

The #[derive(::prost::Enumeration)] annotation added to the generated PhoneType adds these associated functions to the type:

implPhoneType{pubfnis_valid(value:i32) -> bool{ ...}pubfnfrom_i32(value:i32) -> Option<PhoneType>{ ...}}

so you can convert an i32 to its corresponding PhoneType value by doing, for example:

let phone_type = 2i32;matchPhoneType::from_i32(phone_type){Some(PhoneType::Mobile) => ...,Some(PhoneType::Home) => ...,Some(PhoneType::Work) => ...,None => ...,}

Additionally, wherever a proto enum is used as a field in a Message, the message will have 'accessor' methods to get/set the value of the field as the Rust enum type. For instance, this proto PhoneNumber message that has a field named type of type PhoneType:

messagePhoneNumber {
stringnumber=1;
PhoneTypetype=2;
}

will become the following Rust type [1] with methods type and set_type:

pubstructPhoneNumber{pubnumber:String,pubr#type:i32,// the `r#` is needed because `type` is a Rust keyword}implPhoneNumber{pubfnr#type(&self) -> PhoneType{ ...}pubfnset_type(&mutself,value:PhoneType){ ...}}

Note that the getter methods will return the Rust enum's default value if the field has an invalid i32 value.

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.

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

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 for scalar types, Option<T> otherwise
proto3optionalOption<T>
proto2/proto3repeatedVec<T>

Note that in proto3 the default representation for all user-defined message types is Option<T>, and for scalar types just T (during decoding, a missing value is populated by T::default()). If you need a witness of the presence of a scalar type T, use the optional modifier to enforce an Option<T> representation in the generated Rust struct.

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,PartialEq,::prost::Message)]pubstructPerson{#[prost(string, tag="1")]pubname:::prost::alloc::string::String,/// Unique ID number for this person.#[prost(int32, tag="2")]pubid:i32,#[prost(string, tag="3")]pubemail:::prost::alloc::string::String,#[prost(message, repeated, tag="4")]pubphones:::prost::alloc::vec::Vec<person::PhoneNumber>,}/// Nested message and enum types in `Person`.pubmod person {#[derive(Clone,PartialEq,::prost::Message)]pubstructPhoneNumber{#[prost(string, tag="1")]pubnumber:::prost::alloc::string::String,#[prost(enumeration="PhoneType", tag="2")]pubr#type:i32,}#[derive(Clone,Copy,Debug,PartialEq,Eq,Hash,PartialOrd,Ord,::prost::Enumeration)]#[repr(i32)]pubenumPhoneType{Mobile = 0,Home = 1,Work = 2,}}/// Our address book file is just one of these.#[derive(Clone,PartialEq,::prost::Message)]pubstructAddressBook{#[prost(message, repeated, tag="1")]pubpeople:::prost::alloc::vec::Vec<Person>,}

Accessing the protocFileDescriptorSet

The prost_build::Config::file_descriptor_set_path option can be used to emit a file descriptor set during the build & code generation step. When used in conjunction with the std::include_bytes macro and the prost_types::FileDescriptorSet type, applications and libraries using Prost can implement introspection capabilities requiring details from the original .proto files.

Using prost in a no_std Crate

prost is compatible with no_std crates. To enable no_std support, disable the std features in prost and prost-types:

[dependencies]
prost = { version = "0.6", default-features = false, features = ["prost-derive"] }
# Only necessary if using Protobuf well-known types:
prost-types = { version = "0.6", default-features = false }

Additionally, configure prost-build to output BTreeMaps instead of HashMaps for all Protobuf map fields in your build.rs:

letmut config = prost_build::Config::new();
config.btree_map(&["."]);

When using edition 2015, it may be necessary to add an extern crate core; directive to the crate which includes prost-generated code.

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.

Tag Inference for Existing Types

Prost automatically infers tags for the struct.

Fields are tagged sequentially in the order they are specified, starting with 1.

You may skip tags which have been reserved, or where there are gaps between sequentially occurring tag values by specifying the tag number to skip to with the tag attribute on the first field after the gap. The following fields will be tagged sequentially starting from the next number.

use prost;use prost::{Enumeration,Message};#[derive(Clone,PartialEq,Message)]structPerson{#[prost(string, tag = "1")]pubid:String,// tag=1// NOTE: Old "name" field has been removed// pub name: String, // tag=2 (Removed)#[prost(string, tag = "6")]pubgiven_name:String,// tag=6#[prost(string)]pubfamily_name:String,// tag=7#[prost(string)]pubformatted_name:String,// tag=8#[prost(uint32, tag = "3")]pubage:u32,// tag=3#[prost(uint32)]pubheight:u32,// tag=4#[prost(enumeration = "Gender")]pubgender:i32,// tag=5// NOTE: Skip to less commonly occurring fields#[prost(string, tag = "16")]pubname_prefix:String,// tag=16 (eg. mr/mrs/ms)#[prost(string)]pubname_suffix:String,// tag=17 (eg. jr/esq)#[prost(string)]pubmaiden_name:String,// tag=18}#[derive(Clone,Copy,Debug,PartialEq,Eq,Enumeration)]pubenumGender{Unknown = 0,Female = 1,Male = 2,}

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 currently 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.

But it is possible to place serde derive tags onto the generated types, so the same structure can support both prost and Serde.

  1. I get errors when trying to run cargo test on MacOS

If the errors are about missing autoreconf or similar, you can probably fix them by running

brew install automake
brew install libtool

License

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

See LICENSE for details.

Copyright 2022 Dan Burkert & Tokio Contributors

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

6 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - phoenix-dataplane/prost · GitHub
Skip to content

Repository files navigation

continuous integrationDocumentationCrateDependency Status

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 specifier 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:

[dependencies]
prost = "0.10"
# Only necessary if using Protobuf well-known types:
prost-types = "0.10"

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.

See the snazzy repository for a simple start-to-finish example.

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.

protoc

It's recommended to install protoc locally in your path to improve build times. Prost uses protoc to parse protobuf files and will attempt to compile protobuf from source requiring a C++ toolchain. For more info checkout the prost-build docs.

Packages

Prost can now generate code for .proto files that don't have a package spec. prost will translate the Protobuf package into a Rust module. For example, given the package specifier:

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. For example, this proto enum:

enumPhoneType {
MOBILE=0;
HOME=1;
WORK=2;
}

gets this corresponding Rust enum [1]:

pubenumPhoneType{Mobile = 0,Home = 1,Work = 2,}

You can convert a PhoneType value to an i32 by doing:

PhoneType::Mobileasi32

The #[derive(::prost::Enumeration)] annotation added to the generated PhoneType adds these associated functions to the type:

implPhoneType{pubfnis_valid(value:i32) -> bool{ ...}pubfnfrom_i32(value:i32) -> Option<PhoneType>{ ...}}

so you can convert an i32 to its corresponding PhoneType value by doing, for example:

let phone_type = 2i32;matchPhoneType::from_i32(phone_type){Some(PhoneType::Mobile) => ...,Some(PhoneType::Home) => ...,Some(PhoneType::Work) => ...,None => ...,}

Additionally, wherever a proto enum is used as a field in a Message, the message will have 'accessor' methods to get/set the value of the field as the Rust enum type. For instance, this proto PhoneNumber message that has a field named type of type PhoneType:

messagePhoneNumber {
stringnumber=1;
PhoneTypetype=2;
}

will become the following Rust type [1] with methods type and set_type:

pubstructPhoneNumber{pubnumber:String,pubr#type:i32,// the `r#` is needed because `type` is a Rust keyword}implPhoneNumber{pubfnr#type(&self) -> PhoneType{ ...}pubfnset_type(&mutself,value:PhoneType){ ...}}

Note that the getter methods will return the Rust enum's default value if the field has an invalid i32 value.

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.

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

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 for scalar types, Option<T> otherwise
proto3optionalOption<T>
proto2/proto3repeatedVec<T>

Note that in proto3 the default representation for all user-defined message types is Option<T>, and for scalar types just T (during decoding, a missing value is populated by T::default()). If you need a witness of the presence of a scalar type T, use the optional modifier to enforce an Option<T> representation in the generated Rust struct.

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,PartialEq,::prost::Message)]pubstructPerson{#[prost(string, tag="1")]pubname:::prost::alloc::string::String,/// Unique ID number for this person.#[prost(int32, tag="2")]pubid:i32,#[prost(string, tag="3")]pubemail:::prost::alloc::string::String,#[prost(message, repeated, tag="4")]pubphones:::prost::alloc::vec::Vec<person::PhoneNumber>,}/// Nested message and enum types in `Person`.pubmod person {#[derive(Clone,PartialEq,::prost::Message)]pubstructPhoneNumber{#[prost(string, tag="1")]pubnumber:::prost::alloc::string::String,#[prost(enumeration="PhoneType", tag="2")]pubr#type:i32,}#[derive(Clone,Copy,Debug,PartialEq,Eq,Hash,PartialOrd,Ord,::prost::Enumeration)]#[repr(i32)]pubenumPhoneType{Mobile = 0,Home = 1,Work = 2,}}/// Our address book file is just one of these.#[derive(Clone,PartialEq,::prost::Message)]pubstructAddressBook{#[prost(message, repeated, tag="1")]pubpeople:::prost::alloc::vec::Vec<Person>,}

Accessing the protocFileDescriptorSet

The prost_build::Config::file_descriptor_set_path option can be used to emit a file descriptor set during the build & code generation step. When used in conjunction with the std::include_bytes macro and the prost_types::FileDescriptorSet type, applications and libraries using Prost can implement introspection capabilities requiring details from the original .proto files.

Using prost in a no_std Crate

prost is compatible with no_std crates. To enable no_std support, disable the std features in prost and prost-types:

[dependencies]
prost = { version = "0.6", default-features = false, features = ["prost-derive"] }
# Only necessary if using Protobuf well-known types:
prost-types = { version = "0.6", default-features = false }

Additionally, configure prost-build to output BTreeMaps instead of HashMaps for all Protobuf map fields in your build.rs:

letmut config = prost_build::Config::new();
config.btree_map(&["."]);

When using edition 2015, it may be necessary to add an extern crate core; directive to the crate which includes prost-generated code.

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.

Tag Inference for Existing Types

Prost automatically infers tags for the struct.

Fields are tagged sequentially in the order they are specified, starting with 1.

You may skip tags which have been reserved, or where there are gaps between sequentially occurring tag values by specifying the tag number to skip to with the tag attribute on the first field after the gap. The following fields will be tagged sequentially starting from the next number.

use prost;use prost::{Enumeration,Message};#[derive(Clone,PartialEq,Message)]structPerson{#[prost(string, tag = "1")]pubid:String,// tag=1// NOTE: Old "name" field has been removed// pub name: String, // tag=2 (Removed)#[prost(string, tag = "6")]pubgiven_name:String,// tag=6#[prost(string)]pubfamily_name:String,// tag=7#[prost(string)]pubformatted_name:String,// tag=8#[prost(uint32, tag = "3")]pubage:u32,// tag=3#[prost(uint32)]pubheight:u32,// tag=4#[prost(enumeration = "Gender")]pubgender:i32,// tag=5// NOTE: Skip to less commonly occurring fields#[prost(string, tag = "16")]pubname_prefix:String,// tag=16 (eg. mr/mrs/ms)#[prost(string)]pubname_suffix:String,// tag=17 (eg. jr/esq)#[prost(string)]pubmaiden_name:String,// tag=18}#[derive(Clone,Copy,Debug,PartialEq,Eq,Enumeration)]pubenumGender{Unknown = 0,Female = 1,Male = 2,}

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 currently 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.

But it is possible to place serde derive tags onto the generated types, so the same structure can support both prost and Serde.

  1. I get errors when trying to run cargo test on MacOS

If the errors are about missing autoreconf or similar, you can probably fix them by running

brew install automake
brew install libtool

License

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

See LICENSE for details.

Copyright 2022 Dan Burkert & Tokio Contributors

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

6 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); GitHub - phoenix-dataplane/prost · GitHub
Skip to content

Repository files navigation

continuous integrationDocumentationCrateDependency Status

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 specifier 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:

[dependencies]
prost = "0.10"
# Only necessary if using Protobuf well-known types:
prost-types = "0.10"

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.

See the snazzy repository for a simple start-to-finish example.

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.

protoc

It's recommended to install protoc locally in your path to improve build times. Prost uses protoc to parse protobuf files and will attempt to compile protobuf from source requiring a C++ toolchain. For more info checkout the prost-build docs.

Packages

Prost can now generate code for .proto files that don't have a package spec. prost will translate the Protobuf package into a Rust module. For example, given the package specifier:

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. For example, this proto enum:

enumPhoneType {
MOBILE=0;
HOME=1;
WORK=2;
}

gets this corresponding Rust enum [1]:

pubenumPhoneType{Mobile = 0,Home = 1,Work = 2,}

You can convert a PhoneType value to an i32 by doing:

PhoneType::Mobileasi32

The #[derive(::prost::Enumeration)] annotation added to the generated PhoneType adds these associated functions to the type:

implPhoneType{pubfnis_valid(value:i32) -> bool{ ...}pubfnfrom_i32(value:i32) -> Option<PhoneType>{ ...}}

so you can convert an i32 to its corresponding PhoneType value by doing, for example:

let phone_type = 2i32;matchPhoneType::from_i32(phone_type){Some(PhoneType::Mobile) => ...,Some(PhoneType::Home) => ...,Some(PhoneType::Work) => ...,None => ...,}

Additionally, wherever a proto enum is used as a field in a Message, the message will have 'accessor' methods to get/set the value of the field as the Rust enum type. For instance, this proto PhoneNumber message that has a field named type of type PhoneType:

messagePhoneNumber {
stringnumber=1;
PhoneTypetype=2;
}

will become the following Rust type [1] with methods type and set_type:

pubstructPhoneNumber{pubnumber:String,pubr#type:i32,// the `r#` is needed because `type` is a Rust keyword}implPhoneNumber{pubfnr#type(&self) -> PhoneType{ ...}pubfnset_type(&mutself,value:PhoneType){ ...}}

Note that the getter methods will return the Rust enum's default value if the field has an invalid i32 value.

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.

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

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 for scalar types, Option<T> otherwise
proto3optionalOption<T>
proto2/proto3repeatedVec<T>

Note that in proto3 the default representation for all user-defined message types is Option<T>, and for scalar types just T (during decoding, a missing value is populated by T::default()). If you need a witness of the presence of a scalar type T, use the optional modifier to enforce an Option<T> representation in the generated Rust struct.

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,PartialEq,::prost::Message)]pubstructPerson{#[prost(string, tag="1")]pubname:::prost::alloc::string::String,/// Unique ID number for this person.#[prost(int32, tag="2")]pubid:i32,#[prost(string, tag="3")]pubemail:::prost::alloc::string::String,#[prost(message, repeated, tag="4")]pubphones:::prost::alloc::vec::Vec<person::PhoneNumber>,}/// Nested message and enum types in `Person`.pubmod person {#[derive(Clone,PartialEq,::prost::Message)]pubstructPhoneNumber{#[prost(string, tag="1")]pubnumber:::prost::alloc::string::String,#[prost(enumeration="PhoneType", tag="2")]pubr#type:i32,}#[derive(Clone,Copy,Debug,PartialEq,Eq,Hash,PartialOrd,Ord,::prost::Enumeration)]#[repr(i32)]pubenumPhoneType{Mobile = 0,Home = 1,Work = 2,}}/// Our address book file is just one of these.#[derive(Clone,PartialEq,::prost::Message)]pubstructAddressBook{#[prost(message, repeated, tag="1")]pubpeople:::prost::alloc::vec::Vec<Person>,}

Accessing the protocFileDescriptorSet

The prost_build::Config::file_descriptor_set_path option can be used to emit a file descriptor set during the build & code generation step. When used in conjunction with the std::include_bytes macro and the prost_types::FileDescriptorSet type, applications and libraries using Prost can implement introspection capabilities requiring details from the original .proto files.

Using prost in a no_std Crate

prost is compatible with no_std crates. To enable no_std support, disable the std features in prost and prost-types:

[dependencies]
prost = { version = "0.6", default-features = false, features = ["prost-derive"] }
# Only necessary if using Protobuf well-known types:
prost-types = { version = "0.6", default-features = false }

Additionally, configure prost-build to output BTreeMaps instead of HashMaps for all Protobuf map fields in your build.rs:

letmut config = prost_build::Config::new();
config.btree_map(&["."]);

When using edition 2015, it may be necessary to add an extern crate core; directive to the crate which includes prost-generated code.

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.

Tag Inference for Existing Types

Prost automatically infers tags for the struct.

Fields are tagged sequentially in the order they are specified, starting with 1.

You may skip tags which have been reserved, or where there are gaps between sequentially occurring tag values by specifying the tag number to skip to with the tag attribute on the first field after the gap. The following fields will be tagged sequentially starting from the next number.

use prost;use prost::{Enumeration,Message};#[derive(Clone,PartialEq,Message)]structPerson{#[prost(string, tag = "1")]pubid:String,// tag=1// NOTE: Old "name" field has been removed// pub name: String, // tag=2 (Removed)#[prost(string, tag = "6")]pubgiven_name:String,// tag=6#[prost(string)]pubfamily_name:String,// tag=7#[prost(string)]pubformatted_name:String,// tag=8#[prost(uint32, tag = "3")]pubage:u32,// tag=3#[prost(uint32)]pubheight:u32,// tag=4#[prost(enumeration = "Gender")]pubgender:i32,// tag=5// NOTE: Skip to less commonly occurring fields#[prost(string, tag = "16")]pubname_prefix:String,// tag=16 (eg. mr/mrs/ms)#[prost(string)]pubname_suffix:String,// tag=17 (eg. jr/esq)#[prost(string)]pubmaiden_name:String,// tag=18}#[derive(Clone,Copy,Debug,PartialEq,Eq,Enumeration)]pubenumGender{Unknown = 0,Female = 1,Male = 2,}

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 currently 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.

But it is possible to place serde derive tags onto the generated types, so the same structure can support both prost and Serde.

  1. I get errors when trying to run cargo test on MacOS

If the errors are about missing autoreconf or similar, you can probably fix them by running

brew install automake
brew install libtool

License

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

See LICENSE for details.

Copyright 2022 Dan Burkert & Tokio Contributors

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

6 watching

Forks

Releases

Packages

Used by

Contributors

Languages