Config

Struct Config 

Source
#[non_exhaustive]
pub struct Config { /* private fields */ }
Expand description

Configuration that changes how the code generator handles Protobuf types and fields. See configure for how configurations are applied.

Configuration fields are set by chaining builder methods:

Config::new().boxed(true).max_len(12).vec_type("MyVec");

Implementations§

Source§

impl Config

Source

pub fn new() -> Self

Create new config

Source

pub fn max_len(self, val: u32) -> Self

Max number of elements for fixed-capacity repeated and map fields.

This should only be set if vec_type or map_type is a fix-capacity container, because max_len will be used as the 2nd type parameter of the container in the generated code.

For example, if vec_type is ArrayVec and max_len is 5, then the generated container type will be ArrayVec<_, 5>.

Source

pub fn max_bytes(self, val: u32) -> Self

Max number of bytes for fixed-capacity string and bytes fields.

Like with max_len, this should only be set if string_type or vec_type is a fix-capacity container, because max_bytes will be used as the 2nd type parameter of the container in the generated code.

Source

pub fn int_size(self, val: IntSize) -> Self

Override the integer type of integer fields such as int32 or fixed64.

Change the integer fields to be 8, 16, 32, or 64 bytes. If the integer type is smaller than the value on the wire, the value will be truncated to fit.

§Example
// Set type of int32 to `i8`
gen.configure(".Message.int32_field", Config::new().int_size(IntSize::S8));
// Set type of uint32 to `u64`
gen.configure(".Message.uint32_field", Config::new().int_size(IntSize::S64));
§Avoiding 64-bit operations

Setting a 64-bit int field such as int64 or sint64 to >=32 bits makes the code generator use 32-bit operations on that field instead of 64-bit operations. This can have performance benefits on some 32-bit platforms. Setting all int fields to >=32 bits allows micropb’s enable-64bits feature flag to be turned off, disabling 64-bit operations altogether.

Source

pub fn field_attributes(self, s: &str) -> Self

Set attributes for message fields.

The attribute string will be placed before matched fields. The string must be in the syntax of 0 or more Rust attributes.

§Example
// Set field attribute
gen.configure(".Message.foo", Config::new().field_attributes("#[serde(skip)]"));
// Unset field attribute
gen.configure(".Message.foo", Config::new().field_attributes(""));
§Special cases
  • If applied to an oneof field, the attributes are applied to the oneof field of the message struct.
  • If applied to an oneof variant, the attributes are applied to the oneof enum variant in the oneof enum definition.
  • If applied to the ._has suffix, the attributes are applied to the hazzer field of the message struct.
  • If applied to the ._unknown suffix, the attributes are applied to the unknown handler of the message struct.
Source

pub fn boxed(self, val: bool) -> Self

Wrap the field in a Box.

If the field is already wrapped in Option, then the field will be of type Option<Box<_>>.

This config not apply to elements of repeated and map fields.

Source

pub fn vec_type(self, s: &str) -> Self

Container type that’s generated for repeated fields.

For decoding, the provided type must implement PbVec<T>. For encoding, the type must dereference into [T], where T is the type of the element. Moreover, the type must implement Default in order to generate default values.

If the provided type contains the sequence $N, it will be substituted for the value of max_bytes if it’s set for this field. Similarly, the sequence $T will be substituted for the type of the repeated element.

§Example
// assuming that .pkg.Message.list is a repeated field of booleans:

// repeated field configured to `Vec<bool>` (dynamic-capacity)
gen.configure(".pkg.Message.list", Config::new().vec_type("Vec<$T>"));
// repeated field configured to `arrayvec::ArrayVec<bool, 5>` (fixed-capacity)
gen.configure(".pkg.Message.list", Config::new().vec_type("arrayvec::ArrayVec<$T, $N>").max_len(5));
Source

pub fn string_type(self, s: &str) -> Self

Container type that’s generated for string fields.

For decoding, the provided type must implement PbString. For encoding, the type must dereference to str. Moreover, the type must implement Default + TryFrom<&str> in order to generate default values.

If the provided type contains the sequence $N, it will be substituted for the value of max_bytes if it’s set for this field.

§Example
// `string` field configured to `String` (dynamic-capacity)
gen.configure(".pkg.Message.string_field", Config::new().string_type("String"));
// `string` field configured to `ArrayString<4>` (fixed-capacity)
gen.configure(".pkg.Message.string_field", Config::new().string_type("ArrayString<$N>").max_bytes(4));
Source

pub fn bytes_type(self, s: &str) -> Self

Container type that’s generated for bytes fields.

For decoding, the provided type must implement PbBytes. For encoding, the type must dereference to [u8]. Moreover, the type must implement Default + TryFrom<&[u8]> in order to generate default values.

If the provided type contains the sequence $N, it will be substituted for the value of max_bytes if it’s set for this field.

§Example
// `bytes` field configured to `Vec<u8>` (dynamic-capacity)
gen.configure(".pkg.Message.string_field", Config::new().string_type("Vec<u8>"));
// `bytes` field configured to `Vec<u8, 4>` (fixed-capacity)
gen.configure(".pkg.Message.string_field", Config::new().string_type("Vec<u8, $N>").max_bytes(4));
Source

pub fn map_type(self, s: &str) -> Self

Container type that’s generated for map fields.

For decoding, the provided type must implement PbMap. For encoding, the type must implement IntoIterator<Item = (&K, &V)> for &T. Moreover, the type must implement Default in order to generate default values.

If the provided type contains the sequence $N, it will be substituted for the value of max_bytes if it’s set for this field. Similarly, the sequences $K and $V will be substituted for the types of the map key and value respectively.

§Example
// assume that .pkg.Message.map_field is a `map<int32, float>`:

// `map` field configured to `BTreeMap<i32, f32>` (dynamic-capacity)
gen.configure(".pkg.Message.map_field", Config::new().map_type("BTreeMap<$K, $V>"));
// `map` field configured to `FnvIndexMap<i32, f32, 4>` (fixed-capacity)
gen.configure(".pkg.Message.map_field", Config::new().map_type("FnvIndexMap<$K, $V, $N>").max_len(4));
Source

pub fn optional_repr(self, val: OptionalRepr) -> Self

Determine how optional fields are represented.

Presence of optional fields is tracked by either a bitfield in the message struct called a hazzer, or by the Option type. By default, non-boxed fields use hazzers and boxed fields use Option. This behaviour can be customized by setting this option.

§Example
// `optional1: T` with bitfield entry (default unboxed behaviour)
gen.configure(".Message.optional1", Config::new().optional_repr(OptionalRepr::Hazzer));
// `optional2: Option<T>`
gen.configure(".Message.optional2", Config::new().optional_repr(OptionalRepr::Option));
// `optional3: Box<T>` with bitfield entry
gen.configure(".Message.optional3", Config::new().boxed(true)
                                        .optional_repr(OptionalRepr::Hazzer));
// `optional4: Option<Box<T>>` (default boxed behaviour)
gen.configure(".Message.optional4", Config::new().boxed(true)
                                        .optional_repr(OptionalRepr::Option));
Source

pub fn custom_field(self, val: CustomField) -> Self

Replace generated field with an user-provided type. See CustomField for more info.

Substitute a user-provided type as the type of the field. The encoding and decoding behaviour will also be user-provided, so the custom type must implement FieldEncode and FieldDecode and correctly handle the field’s wire representation.

Alternatively, a field can be set to “delegate” to another custom field for encoding and decoding. In that case, the field won’t be generated at all, and its wire value will be handled by the delegated field.

This configuration applies to normal field and oneof fields, but won’t be applied to oneof variants.

§Interaction with other configs

Setting this config option overrides every other config option that affects the field’s generated type, including optional_repr, int_size, and boxed (but not field_attributes). If the field is optional, then the custom type is responsible for tracking field presence, since custom fields aren’t tracked by the hazzer.

§Example
// Make the generator generate `foo: crate::CustomHandler` for field `foo`
gen.configure(
    ".Message.foo",
    Config::new().custom_field(CustomField::from_type("crate::CustomHandler"))
);
// Decoding and encoding of `bar` will also be handled by the `CustomHandler` assigned to `foo`
gen.configure(
    ".Message.bar",
    Config::new().custom_field(CustomField::from_delegate("foo"))
);
Source

pub fn rename_field(self, s: &str) -> Self

Rename a field in the generated Rust struct.

Instead of the protobuf field name, use a different name for the generated field and its accessors. Applies to normal fields as well as oneofs and oneof variants.

§Example
// `super` can't be a field identifier, so we need to rename it
gen.configure(".Message.super", Config::new().rename_field("super_"));
// The oneof field will be renamed to `oneof`, and the oneof type will be `Oneof`
gen.configure(".Message.my_oneof", Config::new().rename_field("oneof"));
§Note

This configuration is only applied to the path passed to configure. It is not propagated to “children” paths.

Source

pub fn encoded_max_size(self, val: usize) -> Self

Override the max size of the field on the wire.

Instead of calculating the max size of the field, the generator will use this value instead when determining the max size of the entire message. This is useful for fields with “unbounded” size, such as Vec fields and recursive fields. Applies to normal fields, oneof fields, and oneof variants.

Source

pub fn field_lifetime(self, s: &str) -> Self

Specify lifetime parameter of a message field.

If message type Inner has fields with a lifetime, its message struct will be generated with that lifetime parameter. However, if another message type Outer has Inner as its field, then that field must specify field_lifetime so that the lifetime is included in the field declaration.

§Example
// `Inner` now has a lifetime param
gen.configure(".Inner.field", Config::new().string_type("MyString<'a>"));
// Make sure inner is declared as `inner: Inner<'a>`
// Will also automatically add the lifetime param to declaration of `Outer`
gen.configure(".Outer.inner", Config::new().field_lifetime("'a"));
Source

pub fn no_accessors(self, val: bool) -> Self

Disable field accessors.

Do not generate accessors for this field other than the getter method on optional fields, which is required by the encoding logic. This won’t reduce the compiled code size, but it will significantly reduce the size of the output source file.

Source

pub fn enum_int_size(self, val: IntSize) -> Self

Override the integer size of Protobuf enums.

Change the integer fields to be i8, i16, i32, or i64. If the integer type is smaller than the value on the wire, the value will be truncated to fit.

Source

pub fn enum_unsigned(self, val: bool) -> Self

Use unsigned integer to represent enums.

Enum will be u32 instead of i32. Negative values on the wire will be truncated, so do not use this if any of the enum variants are negative. Setting this option will reduce the maximum encoded size of the enum, since signed integers always have a max size of 10 bytes.

Source

pub fn type_attributes(self, s: &str) -> Self

Set attributes for generated types, such as messages and enums.

The attribute string will be placed before type definitions. The string must be in the syntax of 0 or more Rust attributes.

§Example
// Set 2 type attributes for Message
gen.configure(".Message", Config::new().type_attributes("#[derive(Eq)] #[MyDerive]"));
// Unset type attributes for Message
gen.configure(".Message", Config::new().type_attributes(""));
§Special cases
  • If applied to an oneof field, the attributes are applied to the oneof enum type definition inside the message.
  • If applied to the ._has suffix, the attributes are applied to the hazzer type definition inside the message.
Source

pub fn no_debug_impl(self, val: bool) -> Self

Disable generating Debug trait derives for message types.

Source

pub fn no_default_impl(self, val: bool) -> Self

Disable generating Default trait impl for message types.

This can cause compile errors if decoding logic is being generated, because decoding repeated and map fields requires the elements to implement Default.

Source

pub fn no_partial_eq_impl(self, val: bool) -> Self

Disable generating PartialEq trait impl for message types.

Source

pub fn no_clone_impl(self, val: bool) -> Self

Disable generating Clone trait derives for message types.

Source

pub fn unknown_handler(self, s: &str) -> Self

Add a custom handler on a message struct for handling unknown fields.

When decoding a message, unknown fields are skipped by default. If a message has unknown_handler configured to a type name, a field of that type named _unknown will be added to the message struct. This field will handle decoding of all unknown fields and will also be encoded, so the handler type must implement FieldEncode and FieldDecode, like with custom_field.

§Note

This configuration is only applied to the path passed to configure. It is not propagated to “children” paths.

Source

pub fn skip(self, val: bool) -> Self

Skip generating a type or field

If applied to message or enum, the whole type definition will be skipped. If applied to a field, it won’t be included in the message struct.

Source§

impl Config

Source

pub fn recursive_field(self) -> Self

Ensure proper handling of a recursive field by boxing it and hardcoding its max size to 0

Combination of Self::boxed and Self::encoded_max_size.

Trait Implementations§

Source§

impl Clone for Config

Source§

fn clone(&self) -> Config

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Config

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Config

Source§

fn default() -> Config

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for Config

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Serialize for Config

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

§

impl Freeze for Config

§

impl RefUnwindSafe for Config

§

impl Send for Config

§

impl Sync for Config

§

impl Unpin for Config

§

impl UnwindSafe for Config

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,