pub struct Config { /* private fields */ }Expand description
Builder for configuring and running protobuf compilation.
Implementations§
Source§impl Config
impl Config
Sourcepub fn generate_adapters(self, enabled: bool) -> Self
pub fn generate_adapters(self, enabled: bool) -> Self
Enable typed (buffa.ext.file).adapters options (default: false).
Native files are written beside the portable output and included
explicitly in their API modules. No native adapter enters the portable
module tree. Missing or incomplete mappings fail before output is written.
Without an explicit Self::adapters configuration, at least one
requested file must declare the options, otherwise compile() fails
with adapters::ErrorReason::MissingSchemaAdapters. This setting
only controls the schema options: it does not suppress an explicit
Self::adapters configuration.
Sourcepub fn adapters(self, config: AdapterConfig) -> Self
pub fn adapters(self, config: AdapterConfig) -> Self
Add descriptor-checked native adapters from a typed Rust configuration. Replaces the previous explicit configuration; schema options, if enabled, are combined with it and checked for collisions.
Sourcepub fn includes(self, includes: &[impl AsRef<Path>]) -> Self
pub fn includes(self, includes: &[impl AsRef<Path>]) -> Self
Add include directories for protoc to search for imports.
Directories are searched in order. If directories overlap, the first matching directory determines the proto-relative file name.
Sourcepub fn out_dir(self, dir: impl Into<PathBuf>) -> Self
pub fn out_dir(self, dir: impl Into<PathBuf>) -> Self
Set the output directory for generated files.
Defaults to $OUT_DIR if not set.
Sourcepub fn generate_views(self, enabled: bool) -> Self
pub fn generate_views(self, enabled: bool) -> Self
Enable or disable view type generation (default: true).
Sourcepub fn lazy_views(self, enabled: bool) -> Self
pub fn lazy_views(self, enabled: bool) -> Self
Additionally generate the lazy view family (FooLazyView<'a>)
alongside the unchanged eager views (default: false).
Lazy views decode in a single non-recursive pass, recording nested and
repeated message fields as undecoded byte ranges that decode on access
via fallible, by-value accessors (.get() / iteration) — untouched
sub-trees cost nothing. Validation of deferred bytes happens on
access (and in the fallible to_owned_message), not at decode.
Groups, oneof message variants, and map message values stay eager;
lazy views have no ReflectMessage/OwnedView/text surface. Eager
codegen output is byte-identical with or without the flag. Requires
generate_views. See
CodeGenConfig::lazy_views for full semantics.
Sourcepub fn generate_json(self, enabled: bool) -> Self
pub fn generate_json(self, enabled: bool) -> Self
Enable or disable serde JSON generation (default: false).
When enabled:
-
Generated message structs get
Serialize/Deserializederives. -
Generated enum types get
Serialize/Deserializederives. -
Generated view types (when
generate_viewsis also enabled) get a manualimpl Serializefor zero-copy JSON serialization, soserde_json::to_string(&view)works directly:ⓘlet view = MyMsgView::decode_view(&bytes)?; let json = serde_json::to_string(&view)?;
The downstream crate must depend on serde and enable the buffa/json
feature for the runtime helpers. When views are enabled, the crate must
also enable buffa-types/json so the well-known type views implement
Serialize; without it, references to e.g. TimestampView<'_> in the
generated Serialize impl will fail with
the trait bound 'TimestampView<'_>: Serialize' is not satisfied.
Limitations of the view Serialize impl:
- Extension fields are not included in view JSON output; serialize the
owned form (
view.to_owned_message()) to include extensions. - The impl uses
serialize_map(None)(unknown length) because the number of emitted fields depends on default-omission rules. Most self-describing serializers (notablyserde_json) accept this, but length-prefixed formats (e.g.bincode,postcard) will return a runtime error. The owned types’ derivedSerializedoes not have this restriction.
Sourcepub fn generate_text(self, enabled: bool) -> Self
pub fn generate_text(self, enabled: bool) -> Self
Enable or disable impl buffa::text::TextFormat on generated message
structs (default: false).
When enabled, the downstream crate must enable the buffa/text
feature for the runtime textproto encoder/decoder.
Sourcepub fn generate_arbitrary(self, enabled: bool) -> Self
pub fn generate_arbitrary(self, enabled: bool) -> Self
Enable or disable #[derive(arbitrary::Arbitrary)] on generated
types (default: false).
The derive is gated behind #[cfg_attr(feature = "arbitrary", ...)]
so the downstream crate compiles with or without the feature enabled.
An enum with a [deprecated = true] variant gets a generated impl
under the same gate instead, because the derive would warn on that
variant. The impl maps input to variants as the derive does.
Your crate’s Cargo feature must be named exactly "arbitrary" —
the generated cfg_attr uses that literal string and cannot be
customised — and it must forward to buffa/arbitrary:
[features]
arbitrary = ["dep:arbitrary", "buffa/arbitrary"]Forgetting "buffa/arbitrary" produces a confusing error in generated
code, such as cannot find function `arbitrary_proto_bytes` in module `buffa::__private` , when a string_type or bytes_type rule selects
a non-default type: the functions that back #[arbitrary(with = ...)]
on those fields live in buffa under that feature gate.
Sourcepub fn skip_debug(self, paths: &[impl AsRef<str>]) -> Self
pub fn skip_debug(self, paths: &[impl AsRef<str>]) -> Self
Omit the generated Debug implementation for the matching messages
and enums, so that your crate can write its own.
Each path is a fully-qualified proto path. For messages it is a
prefix: ".demo.Uuid4" names that message and the messages nested
inside it, ".demo" every message in the package and its
sub-packages, and "." every message. A matched message’s oneof
enums lose their Debug with it. An enum loses its Debug only when
a path is its exact name, such as ".demo.Level": a message or
package path leaves the enums under it as they are. A leading dot is
added if missing and trailing dots are trimmed. Repeated calls
accumulate.
Eager, lazy, and owned views of matched messages, and their view oneofs,
keep Debug but print only the type name and [REDACTED]. This also
hides preserved unknown wire fields. The rule affects generated
formatting only. For selective redaction in generated and reflective
formatting, use [debug_redact = true]. A hand-written Debug impl
for a matched owned message or oneof decides what that value prints.
Your crate then implements Debug:
- for every matched enum, because
buffa::Enumerationrequires it; - for a matched message that an unmatched message or oneof holds
(their generated
Debugformats it), that is generated with reflection, or that a customrepeated_typecollection holds; - for a matched message’s oneof enum, if your
Debugfor the message prints it. For a oneofkindindemo.Uuid4the enum isdemo::uuid4::Kind.
A missing impl is a compile error. For an enum it is error E0277
(Level doesn’t implement Debug) at the generated
impl ::buffa::Enumeration for Level. A path that matches no
generated message and names no generated enum prints a
cargo:warning.
§Example
// build.rs
buffa_build::Config::new()
.files(&["proto/demo.proto"])
.includes(&["proto/"])
.skip_debug(&[".demo.Uuid4", ".demo.Level"])
.compile()?;
// src/lib.rs
pub mod demo {
buffa::include_proto!("demo");
}
impl core::fmt::Debug for demo::Uuid4 {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "Uuid4({:016x}{:016x})", self.msb, self.lsb)
}
}
// Prints the value's proto name, as the derive it replaces does.
impl core::fmt::Debug for demo::Level {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(buffa::Enumeration::proto_name(self))
}
}Sourcepub fn deny_view_json(self, paths: &[impl AsRef<str>]) -> Self
pub fn deny_view_json(self, paths: &[impl AsRef<str>]) -> Self
Reject JSON serialization of the selected messages’ eager, lazy and owned
views before writing any output. Owned-message JSON remains available.
The restriction propagates to containing messages, including map values.
. selects every message; unmatched rules cause a code generation error.
Empty paths are errors. Disabling JSON or views warns that the rule is inactive.
Sourcepub fn borrowed_views_only_in(self, paths: &[impl AsRef<str>]) -> Self
pub fn borrowed_views_only_in(self, paths: &[impl AsRef<str>]) -> Self
Omit standard owned-view wrappers and HasMessageView for matching
messages and their containers. Borrowed views remain available.
Use . to select every message. Rules must match a known message.
Messages selected for cleanup, and their containers, are always
treated as selected.
This controls what code is generated. It does not disable explicit
use of the public buffa::OwnedView runtime with a borrowed view type.
Sourcepub fn gate_impls_on_crate_features(self, enabled: bool) -> Self
pub fn gate_impls_on_crate_features(self, enabled: bool) -> Self
Wrap generated impls in #[cfg(feature = "...")] instead of
emitting them unconditionally (default: false).
When enabled, the impls controlled by generate_json,
generate_views, and generate_text are wrapped in
#[cfg(feature = "json" | "views" | "text")] (or
#[cfg_attr(feature = ..., ...)] for derives and field attributes)
rather than emitted unconditionally. The crate consuming the
generated code must define matching Cargo features that enable the
corresponding runtime support:
[features]
json = ["buffa/json", "dep:serde", "dep:serde_json"]
views = []
text = ["buffa/text"]The generate_* flags still control whether an impl kind is
emitted at all — this flag only controls whether it is cfg-gated.
generate_arbitrary is always cfg_attr-gated on
feature = "arbitrary" regardless of this flag, because arbitrary
is an optional dependency by design.
Reach for this when generated code is the public interface of a
library crate consumed by downstream projects with different
feature needs — exactly the shape of buffa-descriptor and
buffa-types, which ship every impl while letting the codegen
toolchain (buffa-codegen/buffa-build/protoc-gen-reallyme-buffa) depend
on them with default-features = false and stay free of
serde/serde_json/base64. Most consumers of buffa-build are
not in this position: a build.rs that decides at build-script
time whether to generate JSON wants impl Serialize to just exist.
Default false.
Sourcepub fn json_feature_name(self, name: impl Into<String>) -> Self
pub fn json_feature_name(self, name: impl Into<String>) -> Self
Set the crate feature name the gated JSON impls are conditioned on
(default: "json").
Only meaningful together with
gate_impls_on_crate_features;
inert otherwise. Use when the consuming crate gates its JSON support
behind a differently-named feature:
[features]
serde = ["buffa/json", "dep:serde", "dep:serde_json"]buffa_build::Config::new()
.generate_json(true)
.gate_impls_on_crate_features(true)
.json_feature_name("serde")The name is emitted verbatim into #[cfg(feature = "...")]
attributes and must be a valid Cargo feature name declared in the
consuming crate’s [features] table. A misspelled or undeclared
name fails open: the #[cfg] is permanently false, so the gated
impls silently compile away (on Rust ≥ 1.80 an undeclared name at
least triggers the unexpected_cfgs warning). A name that is not a
valid Cargo feature name at all (empty, or containing characters
outside alphanumerics and _/-/+/.) makes compile
fail with an error when the gate is active.
Sourcepub fn views_feature_name(self, name: impl Into<String>) -> Self
pub fn views_feature_name(self, name: impl Into<String>) -> Self
Set the crate feature name the gated view impls are conditioned on
(default: "views").
Only meaningful together with
gate_impls_on_crate_features;
inert otherwise. See json_feature_name.
Sourcepub fn text_feature_name(self, name: impl Into<String>) -> Self
pub fn text_feature_name(self, name: impl Into<String>) -> Self
Set the crate feature name the gated textproto impls are conditioned
on (default: "text").
Only meaningful together with
gate_impls_on_crate_features;
inert otherwise. See json_feature_name.
Sourcepub fn reflect_feature_name(self, name: impl Into<String>) -> Self
pub fn reflect_feature_name(self, name: impl Into<String>) -> Self
Set the crate feature name the gated reflection impls are conditioned
on (default: "reflect").
Only meaningful together with
gate_impls_on_crate_features
(or the experimental, hidden gate_reflect_on_crate_feature, which
gates reflection alone); inert otherwise. See
json_feature_name.
Sourcepub fn type_name_prefix(self, prefix: impl Into<String>) -> Self
pub fn type_name_prefix(self, prefix: impl Into<String>) -> Self
Prepend a prefix to every generated Rust type name (default: none).
With prefix "Rpc", message User {} generates struct RpcUser
(and RpcUserView / RpcUserOwnedView); every cross-reference uses
the prefixed name. Useful in multi-protocol systems where generated
types from different domains would otherwise collide with each other
or with a canonical hand-written model.
Applies to message structs and enum types (top-level and nested).
Module names, oneof enums, extern_path-mapped
types (including well-known types), and the wire/JSON format are
unaffected.
When another crate references these prefixed types via its own
extern_path mapping, the mapped Rust path must
spell out the prefixed name (e.g. ::crate_a::RpcUser) — the proto
name carries no prefix, so the mapping is not derived automatically.
The prefix must be PascalCase ([A-Z][A-Za-z0-9]*) — an ASCII
uppercase letter followed by ASCII letters and digits — so the
prefixed names stay conventionally cased; compile
fails otherwise.
Sourcepub fn generate_with_setters(self, enabled: bool) -> Self
pub fn generate_with_setters(self, enabled: bool) -> Self
Enable or disable with_* builder-style setter methods for
explicit-presence fields (default: true).
Each explicit-presence scalar, bytes, or enum field gets a
pub fn with_<name>(mut self, value: T) -> Self method that wraps the
value in Some(...) and returns self, enabling chained construction
without the Some(...) boilerplate:
let req = MyRequest::default()
.with_name("alice")
.with_timeout_ms(30_000);String, bytes, and enum setters take impl Into<T> (so &str,
b"..." literals, and bare enum variants work directly); other
scalars take T to keep integer-literal inference unambiguous.
Setters are pure inherent methods with no runtime dependency — they
don’t interact with the json/views/text feature gates. Disable
only if you want to keep generated code minimal or have a competing
with_* convention in your own crate.
Sourcepub fn generate_reflection(self, enabled: bool) -> Self
pub fn generate_reflection(self, enabled: bool) -> Self
Enable reflection on generated types (default: off).
generate_reflection(true) selects ReflectMode::VTable — the fast
path: foo.reflect() borrows foo directly (no encode/decode
round-trip), and owned and view types implement ReflectMessage. For
the smaller bridge implementation (reflect() round-trips through a
DynamicMessage), use reflect_mode(ReflectMode::Bridge)
instead. generate_reflection(false) is ReflectMode::Off.
Either mode embeds a lazily-built DescriptorPool (as
FileDescriptorSet bytes) reachable as
your_crate::your_pkg::descriptor_pool().
§Cargo.toml setup
The consuming crate must depend on buffa-descriptor with the
reflect feature and on std:
[dependencies]
buffa = { package = "reallyme-buffa", version = "=0.1.3", features = ["std"] }
buffa-descriptor = { package = "reallyme-buffa-descriptor", version = "=0.1.3", features = ["reflect", "std"] }When gate_impls_on_crate_features
is also on, the impls are wrapped in #[cfg(feature = "reflect")],
so the consuming crate must declare a forwarding feature:
[features]
reflect = ["buffa-descriptor/reflect"]Without the feature declared, the generated Reflectable impls
silently disappear — cfg(feature = "reflect") is permanently
false in a crate that doesn’t declare it. The first call to
.reflect() fails to compile with “trait Reflectable not
implemented”, which is a misleading diagnostic. Most consumers
should leave gate_impls_on_crate_features off.
Reflecting message-typed fields also requires every crate that field
types resolve to via an extern path — notably buffa-types for
well-known types — to enable its own reflection feature; see
reflect_mode (“Extern-path types”) for the
Cargo.toml requirement and mixed-mode behavior.
§Performance
In the default vtable mode, reflect() borrows self — no round-trip,
no allocation; reflective accessors read fields in place. (Bridge mode
instead pays one encode/decode round-trip plus a heap allocation per
call.) Either way the first call pays a one-time pool build cost.
§Build time and binary size
By default each generated package embeds its own copy of the full
FileDescriptorSet (transitive closure). For a single-package
crate this is one copy. For a multi-package codegen run the bytes
duplicate per package — measurable for large proto trees;
shared_descriptor_pool collapses that
to one include_bytes! sidecar. The serialization happens once per
compile() call (not per package), so build-time CPU does not scale
with package count. Vtable mode also emits an impl ReflectMessage per
type, so it produces more code than bridge mode.
Sourcepub fn reflect_mode(self, mode: ReflectMode) -> Self
pub fn reflect_mode(self, mode: ReflectMode) -> Self
Select the reflection mode (the fuller form of
generate_reflection).
ReflectMode::Off— no reflection (the default); equivalent togenerate_reflection(false).ReflectMode::Bridge—reflect()round-trips throughDynamicMessage; smaller generated code, slower reflective access.ReflectMode::VTable—impl ReflectMessageon owned and view types, andreflect()borrowsselfwith no round-trip; equivalent togenerate_reflection(true). Does not require view generation — with views off, only the owned impls are emitted.
All non-Off modes require the consuming crate to depend on
buffa-descriptor with its reflect feature and on std. The call
site (foo.reflect().get(fd)) is identical across modes.
§Extern-path types
Reflection on a message reaches into its message-typed fields, so
every crate that field types resolve to via an extern path must have
its own reflection enabled. In particular, well-known types resolve
to buffa-types by default, and its impls are behind a cargo
feature: depend on buffa-types = { ..., features = ["reflect"] }
or the build fails with unsatisfied Reflectable /
ReflectMessage bounds on the WKT.
§Mixed modes
A vtable-mode message may embed owned message types generated in
bridge mode (e.g. a dependency crate that chose the smaller output):
reflective access degrades to an owned DynamicMessage snapshot at
that boundary instead of failing. For a bridge-grade repeated or
map field the snapshot is taken per element on every access, so
reflecting a large mixed-mode collection scales the encode/decode
cost by the element count. The view reflection surface cannot
degrade — every view type embedded in a vtable-mode view must itself
be vtable-grade, and a bridge-grade view field is a compile error.
Deduplicate the embedded reflection descriptor pool across packages.
With reflection enabled, each package normally embeds its own copy of
the full-closure FileDescriptorSet. For a multi-package build those
copies are identical, so a large proto tree carries the same bytes once
per package. When this is on, the descriptor set is written once as a
binary sidecar next to the generated tree and include_bytes!-d by a
single shared __buffa_fds module; every package’s descriptor_pool()
/ FILE_DESCRIPTOR_SET_BYTES delegates to it. This removes both the
per-package duplication and the byte-literal source expansion.
The sidecar is named <include-file-stem>.descriptor_set.binpb (so
.include_file("gen_mod.rs") writes gen_mod.descriptor_set.binpb)
and lands in the output directory next to the include file. With a
checked-in out_dir, commit the sidecar alongside
the generated .rs files — the include_bytes! resolves relative to
the include file, so the pair must travel together.
Requires include_file (the shared module is
emitted into that file at the tree root) and reflection to be enabled;
compile errors otherwise. The include file name must
be a bare file name, not a path: the sidecar is named after the stem
alone, so a/gen.rs and b/gen.rs would share one sidecar. See
CodeGenConfig::shared_descriptor_pool.
In this mode the generated tree must be consumed through the include
file (include!(concat!(env!("OUT_DIR"), "/gen_mod.rs")), or the
checked-in mod gen; flavour). Each package delegates to __buffa_fds
by a fixed number of super:: hops from the tree root, so wiring
packages individually with buffa::include_proto! does not compile
here: the delegation resolves against whatever module the macro lands
in. Two shared-pool compile() calls included at the same module scope
likewise collide on __buffa_fds; give each include file its own
module.
Sourcepub fn idiomatic_enum_aliases(self, enabled: bool) -> Self
pub fn idiomatic_enum_aliases(self, enabled: bool) -> Self
Enable or disable idiomatic UpperCamelCase enum aliases (matches the
CodeGenConfig default, currently on).
Protobuf enum values are SHOUTY_SNAKE_CASE and stay the definitive Rust
variants. When enabled, codegen additionally emits associated consts
with the enum-name prefix stripped and the name converted to
UpperCamelCase (RULE_LEVEL_HIGH → RuleLevel::High), purely
additively — existing references and Debug output are unchanged.
Aliases are suppressed per enum (with a build warning and a doc note) if
any two values would collide after conversion, so a match is never forced
to mix conventions. See CodeGenConfig::idiomatic_enum_aliases.
Sourcepub fn idiomatic_field_names(self, enabled: bool) -> Self
pub fn idiomatic_field_names(self, enabled: bool) -> Self
Convert proto field and oneof names to idiomatic snake_case Rust
identifiers (webMessageInfo → web_message_info), matching
prost-build’s behavior for protos that use camelCase field names.
Default: false (proto names are emitted verbatim).
Only the generated Rust source names change; the wire format, JSON
(json_name plus the original proto name accepted on parse), text
format, and reflection lookups all keep the descriptor’s names, so the
option is fully wire- and JSON-compatible. Enum values are covered by
idiomatic_enum_aliases instead.
Word boundaries match prost-build’s (heck’s) segmentation, including
digit-transparent case boundaries (v2Field → v2_field); unlike
prost, authored underscores are always preserved (_foo stays
_foo), so already-snake_case names are never rewritten.
If two members of one message collide after conversion (userName and
user_name — rejected by protoc for proto3/editions, so proto2 only),
the names are adjusted deterministically and a build warning is
emitted; see CodeGenConfig::idiomatic_field_names for the rules.
Sourcepub fn file_per_package(self, enabled: bool) -> Self
pub fn file_per_package(self, enabled: bool) -> Self
Emit one <dotted.package>.rs file per proto package instead of the
per-proto-file content set plus <pkg>.mod.rs stitcher. Default:
false.
The single file inlines what the stitcher would otherwise include!,
producing the same module structure. Required by
idiomatic_imports. See
CodeGenConfig::file_per_package for caveats about packages that
span multiple directories.
Sourcepub fn idiomatic_imports(self, enabled: bool) -> Self
pub fn idiomatic_imports(self, enabled: bool) -> Self
Experimental. Emit use-backed short type names at the package
root instead of fully-qualified paths, so struct fields read
MessageField<Timestamp> instead of
::buffa::MessageField<::buffa_types::google::protobuf::Timestamp>.
Default: false (output is byte-for-byte identical to previous
releases).
Requires file_per_package — the build
fails otherwise. Short names that would collide with another item at
the package root (or a name referenced bare by sibling emissions)
fall back to parent-module qualification, then to the
fully-qualified path.
Only package-root type declarations are shortened; impl bodies,
nested-message modules, and __buffa internals keep fully-qualified
paths. “Experimental” means the output shape may change between
releases and the option may be renamed or removed outside semver
guarantees. See CodeGenConfig::idiomatic_imports for details.
Sourcepub fn preserve_unknown_fields(self, enabled: bool) -> Self
pub fn preserve_unknown_fields(self, enabled: bool) -> Self
Enable or disable unknown field preservation (default: true).
When enabled (the default), unrecognized fields encountered during decode are stored and re-emitted on encode — essential for proxy / middleware services and round-trip fidelity across schema versions.
Disabling is mostly a memory optimization: 24 bytes per owned
message for the UnknownFields Vec header, and one pointer per
view, whose backing state is allocated only once an unknown field
actually arrives.
A wire payload with no unknown fields does no per-field work either
way, but that does not make the two modes equivalent: carrying the
handle still shapes how the compiler moves the view, and that is
measurable on view-decode throughput for message-dense shapes.
Disabling is the only setting that removes the field outright, so it
is the lever to reach for when view decode is hot and round-trip
fidelity across schema versions is not required — as it is for
embedded / no_std targets and large in-memory collections of small
messages.
To keep the global off-switch and still preserve selected messages, use
preserve_unknown_fields_in.
Sourcepub fn generate_zeroize(self, enabled: bool) -> Self
pub fn generate_zeroize(self, enabled: bool) -> Self
Generate recursive cleanup for every owned message.
Requires buffa/zeroize and guarded field representations; see the guarded-fields guide.
No owned-view wrapper or HasMessageView impl is generated, as with
borrowed_views_only_in.
Sourcepub fn zeroize_in(self, paths: &[impl AsRef<str>]) -> Self
pub fn zeroize_in(self, paths: &[impl AsRef<str>]) -> Self
Generate recursive cleanup for messages under these proto path prefixes.
. matches every message. Calls accumulate. Empty or unmatched paths
are errors; scoped requests can explicitly allow unmatched rules.
Selected messages and their containers get no owned-view wrapper or
HasMessageView impl, as with
borrowed_views_only_in.
Sourcepub fn preserve_unknown_fields_in(self, paths: &[impl AsRef<str>]) -> Self
pub fn preserve_unknown_fields_in(self, paths: &[impl AsRef<str>]) -> Self
Enable unknown-field preservation for matching messages, on top of
the global preserve_unknown_fields
setting.
Each path is a fully-qualified proto path prefix, e.g.
".wa.CallLogRecord" for one message or ".wa" for a package (same
matching as unbox_oneof_in); "." matches
every message. A leading dot is added if missing and trailing dots
are trimmed. An empty path is warned about and ignored so "."
remains the only catch-all spelling.
A rule covers the message it names and every message nested inside
it; a rule naming a nested message does not cover its enclosing
message. Rules are enable-only, so this builder cannot exclude a
nested message from a rule that names its parent
(CodeGenConfig::preserve_unknown_fields_in
also accepts disabling entries, and the last matching entry wins).
Preservation is a property of each message type: a preserved
message’s sub-messages keep their own unknown fields only if their
types are covered too.
Repeated calls accumulate. The call order relative to
preserve_unknown_fields does not
matter; the rules apply on top of whichever global value is in force
at compile time. They only change the outcome when
the global setting is off. A rule that matches no generated message
produces a cargo:warning from this build (surfaced via
CodeGenWarning), since an inert
rule silently loses round-trip fidelity for the type it was meant to
keep.
A message that does not preserve unknown fields has no
__buffa_unknown_fields field, and so also loses everything built on
it: the ExtensionSet impl (extension() / set_extension() /
has_extension()), ReflectMessage::unknown_fields, extension
round-tripping through textproto, and [ext] keys in JSON.
buffa_build::Config::new()
.preserve_unknown_fields(false)
.preserve_unknown_fields_in(&[".wa.CallLogRecord", ".wa.SyncdMutation"])Sourcepub fn deny_unknown_json_fields(self, enabled: bool) -> Self
pub fn deny_unknown_json_fields(self, enabled: bool) -> Self
Make generated JSON deserializers reject unknown keys instead of
ignoring them (default: false, unknown keys are ignored).
Strictness is fixed in the generated type: code that uses the type
cannot switch it per call or per process. To be strict for selected
messages only, use
deny_unknown_json_fields_in.
With generate_json off there are no JSON
deserializers, so the option changes nothing and the build emits a
cargo:warning saying so.
The guide’s “Unknown fields in JSON” section covers the error a
rejected key produces, how "[pkg.ext]" extension keys are treated,
and what to weigh before enabling this for every message.
Sourcepub fn deny_unknown_json_fields_in(self, paths: &[impl AsRef<str>]) -> Self
pub fn deny_unknown_json_fields_in(self, paths: &[impl AsRef<str>]) -> Self
Reject unknown JSON fields for matching messages, on top of the global
deny_unknown_json_fields setting.
Each path is a fully-qualified proto path prefix, e.g. ".demo.Config"
for one message or ".demo" for a package (same matching as
preserve_unknown_fields_in);
"." matches every message. A leading dot is added if missing and
trailing dots are trimmed. An empty path is warned about and ignored so
"." remains the only catch-all spelling.
A rule covers the message it names and every message nested inside it; a rule naming a nested message does not cover its enclosing message. Strictness is a property of each message type: a strict message’s sub-messages reject unknown keys only if their types are covered too.
Rules only enable, so this builder cannot exempt a message. With the
global flag on, every message is already strict and these rules add
nothing; to be strict everywhere except a few messages, leave the
global flag off and list the strict packages here.
(buffa_codegen::CodeGenConfig accepts disabling entries; neither
this builder nor the plugin exposes them.) With
generate_json off the rules change nothing,
and the build warns as it does for the global flag.
Repeated calls accumulate. A rule that matches no generated message
produces a cargo:warning from this build (surfaced via
CodeGenWarning), since an inert rule
leaves the message silently ignoring the keys it was meant to reject.
buffa_build::Config::new()
.generate_json(true)
.deny_unknown_json_fields_in(&[".demo.DeviceConfig"])Sourcepub fn override_feature_in(
self,
path: impl AsRef<str>,
feature: FeatureOverride,
) -> Self
pub fn override_feature_in( self, path: impl AsRef<str>, feature: FeatureOverride, ) -> Self
Apply a path-scoped editions FeatureOverride to the compiled
descriptors before generation.
This is buffa’s mechanism for integrators who must work with protos
they cannot modify: editions unification models proto2 and proto3 as
editions with fixed feature defaults, and an override behaves as if
the proto had been migrated to editions with that feature set at the
matched paths. The supported overrides are the FeatureOverride
variants — each is admitted only once buffa’s codegen, runtime, and
validation handle the descriptor states it can create. Overrides
never change the wire format.
path is a fully-qualified proto path prefix. A rule may name a type
(for example, ".my.pkg.Status"), a field
(".my.pkg.Response.status"), a package/message prefix, or "." for
everything the override targets. A leading dot is added if missing.
Map enum values match the outer map field path; oneof enum variants
match the direct field path. An empty path is warned about and
ignored so "." remains the only global opt-in spelling. (The
protoc-gen-reallyme-buffa plugin’s override_feature_in= option rejects
empty paths with a hard error instead: a stray build-script entry
shouldn’t fail the build, but plugin options are usually
machine-assembled, where an empty value is a bug.)
Repeated calls accumulate; rule order does not matter. A rule that
matches nothing produces a cargo:warning from this build (surfaced
via CodeGenWarning), since an
inert rule silently leaves the affected paths on the semantics the
override exists to change.
Under reflection, the embedded descriptor pool carries the injected
features, so runtime reflection and descriptor-driven dynamic JSON
stay consistent with the generated types for both enum-scoped and
field-scoped rules. A field-scoped injection is buffa-specific,
though: other runtimes reading the exported descriptor set ignore it.
See FeatureOverride::EnumType for how the two scopes differ.
Sourcepub fn open_enums_in(self, paths: &[impl AsRef<str>]) -> Self
pub fn open_enums_in(self, paths: &[impl AsRef<str>]) -> Self
Treat selected closed enums (or closed enum fields) as open in the
generated representation — shorthand for
override_feature_in(path, FeatureOverride::EnumType(EnumTypeOverride::Open))
applied to each path.
Matching closed enum fields generate as EnumValue<E> instead of E,
so unknown wire values are directly visible as EnumValue::Unknown(n).
This is an opt-in migration / interop mode: it deliberately changes
closed-enum presence behavior for matching fields, making an unknown
value read as present instead of unset with the raw value represented
through unknown fields. An enum-type rule opens the enum itself, so
every field referencing it is affected; a field rule opens just that
field, leaving the enum’s own declared openness unchanged. Both are
honored by buffa’s descriptor-driven codecs, which resolve openness
per field. Prefer enum-type rules when the descriptor set leaves the
process: a field-level enum_type is not a spec-valid editions
feature, so other runtimes reading the exported set ignore it. That
preference does not help for an enum reached through extern_path —
its descriptor is not in the compiled set to mutate, so even an
enum-type rule is carried as a field-level override. Path grammar,
accumulation, and inert-rule warnings are as described on
override_feature_in.
Sourcepub fn strict_utf8_mapping(self, enabled: bool) -> Self
pub fn strict_utf8_mapping(self, enabled: bool) -> Self
Honor features.utf8_validation = NONE by emitting Vec<u8> / &[u8]
for such string fields instead of String / &str (default: false).
When disabled (the default), all string fields map to String and
UTF-8 is validated on decode — stricter than proto2 requires, but
ergonomic and safe.
When enabled, string fields with utf8_validation = NONE become
Vec<u8> / &[u8]. Decode skips validation; the caller chooses
whether to std::str::from_utf8 (checked) or from_utf8_unchecked
(trusted-input fast path). This is the only sound Rust mapping when
strings may actually contain non-UTF-8 bytes.
Note for proto2 users: proto2’s default is utf8_validation = NONE,
so enabling this turns ALL proto2 string fields into Vec<u8>. Use
only for new code or when profiling identifies UTF-8 validation as a
bottleneck (it can be 10%+ of decode CPU for string-heavy messages).
JSON note: fields normalized to bytes serialize as base64 in JSON
(the proto3 JSON encoding for bytes). Keep strict mapping disabled
for fields that need JSON string interop with other implementations.
Interaction with use_bytes_type: when both are enabled,
map<bytes, bytes> values stay Vec<u8> (the bytes-keyed JSON helper
is concrete HashMap<Vec<u8>, Vec<u8>>). All other bytes shapes —
singular / optional / repeated / oneof / map<non-bytes, bytes> —
still become bytes::Bytes. The asymmetry is documented; if you hit
it, see issue #76.
Sourcepub fn allow_message_set(self, enabled: bool) -> Self
pub fn allow_message_set(self, enabled: bool) -> Self
Permit option message_set_wire_format = true on input messages.
MessageSet is a legacy Google-internal wire format. Default: false
(such messages produce a codegen error). Set to true only when
compiling protos that interoperate with old Google-internal services.
Sourcepub fn extern_path(
self,
proto_path: impl Into<String>,
rust_path: impl Into<String>,
) -> Self
pub fn extern_path( self, proto_path: impl Into<String>, rust_path: impl Into<String>, ) -> Self
Declare an external type path mapping.
The matched types reference the specified Rust path instead of being generated. This allows shared proto packages to be compiled once in a dedicated crate and referenced from others.
proto_path is a fully-qualified protobuf path — either a package
(".my.common", mapping every type under it to a Rust module root) or a
single type FQN (".google.protobuf.Timestamp", mapping just that
type, the prost/tonic idiom). The leading dot is optional and is added
automatically. As in prost, the most specific entry wins: an exact type
FQN beats a covering package prefix, which in turn beats a shorter
prefix.
rust_path is where the type(s) are accessible — a module root for a
package mapping (e.g. "::common_protos") or a full type path for a
per-type mapping (e.g. "::pbjson_types::Timestamp"). It must be an
absolute path (starting with :: or crate::); any other value is
emitted into the generated code verbatim and will fail to resolve there.
Nested types inherit an enclosing message’s per-type override:
mapping .my.pkg.Outer to ::ext::Outer resolves .my.pkg.Outer.Inner
to ::ext::outer::Inner — the override’s parent module plus buffa’s
usual snake_case(MessageName) nested-types module (snake case of the
proto message name, regardless of the override’s final segment). This
matches the layout of another buffa-generated crate; for a target crate
laid out differently, add explicit per-type entries for the nested types
as well.
§Limitations
An extern type that is referenced by a generated view must map to
another buffa-generated crate — the view path is composed as
<rust_path_root>::__buffa::view::…, which a non-buffa crate (e.g.
pbjson_types) does not provide. Map per-type to a buffa crate, or
disable views (generate_views(false)), for
such types.
When JSON generation is enabled, an external message routed through a
ProtoJSON container helper must implement
buffa::json_helpers::ProtoElemJson so generated containers can apply
ProtoJSON encoding and reject null elements/values. This includes
external wrapper types in repeated/map fields and external message
values in bytes-keyed maps; ordinary message containers use serde
directly.
proto_path is . or a dotted protobuf package or type name. The
leading dot is optional and one trailing dot is ignored;
compile returns an error for a name with an empty
segment (my..common) or a segment that is not a protobuf identifier.
Other misconfigurations (a typo’d FQN target, a non-absolute
rust_path, or a view-referenced type mapped to a non-buffa crate)
are not diagnosed at generation time; they surface as an
unresolved-path error when the generated code is compiled.
§Example
buffa_build::Config::new()
// Whole-package mapping.
.extern_path(".my.common", "::common_protos")
// Per-type mapping (issue #111) — overrides the package prefix for
// just this type.
.extern_path(".google.protobuf.Timestamp", "::common_protos::well_known::Timestamp")
.files(&["proto/my_service.proto"])
.includes(&["proto/"])
.compile()
.unwrap();Sourcepub fn exclude_package(self, package: impl Into<String>) -> Self
pub fn exclude_package(self, package: impl Into<String>) -> Self
Exclude a proto package from code generation.
package is the proto package to exclude (e.g. "buf.validate",
".gnostic.openapi.v3"). A leading dot is optional and stripped
automatically. The package and all of its sub-packages are excluded:
"buf.validate" drops both buf.validate and buf.validate.priv.
Use this when proto files from option-only packages (e.g.
buf/validate/validate.proto, gnostic annotations) end up in the
generate set through directory globbing, but you do not want Rust types
generated for those packages. Their descriptors remain available for
cross-package type resolution; only code generation is skipped.
Warning: if any kept file references an excluded package as a field
type, the generated code will contain dangling super::…::Type paths
that fail to compile; the build emits a cargo:warning naming the
file, message, and field before that happens. Pair exclude_package with
extern_path to map the excluded types to an
external crate, or do not list those .proto files in
files.
This method can be called multiple times to exclude multiple packages.
§Validation
compile returns an error, before running protoc, if
package is empty or contains invalid components (empty segments,
consecutive dots). A single leading dot is allowed and stripped.
§Example
buffa_build::Config::new()
.exclude_package("buf.validate")
.exclude_package(".gnostic.openapi.v3")
.files(&["proto/my_service.proto"])
.includes(&["proto/", "vendor/"])
.compile()
.unwrap();Sourcepub fn use_bytes_type_in(self, paths: &[impl AsRef<str>]) -> Self
pub fn use_bytes_type_in(self, paths: &[impl AsRef<str>]) -> Self
Configure bytes fields to use bytes::Bytes instead of Vec<u8>.
Each path is a fully-qualified proto path prefix. Use "." to apply
to all bytes fields, or specify individual field paths like
".my.pkg.MyMessage.data". Path normalization and the warning for a
rule that matches nothing are as described on
bytes_type_in.
Applies uniformly to singular, optional, repeated, oneof, and
map<K, bytes> values — the map case lets view → owned
conversion participate in the to_owned_from_source zero-copy
slice_ref path. One carve-out: an effective map<bytes, bytes> keeps
Vec<u8> values (the JSON helper for that combination is concrete
HashMap<Vec<u8>, Vec<u8>>); every other shape becomes Bytes. A
bytes map key is only reachable when strict_utf8_mapping is enabled
and the map<string, bytes> field carries
[features.utf8_validation = NONE] on its key, which normalizes the
string key to bytes — strict_utf8_mapping alone does not trigger it.
A custom bytes representation
(bytes_type_custom) is honored for
map<K, bytes> values too, the same as the built-in Bytes — but a
custom map value (like a custom repeated element) must be a crate-local
type, since codegen emits its ReflectElement / InspectElement /
ProtoElemJson impls (the orphan rule forbids them for a foreign type).
A type listed with json_policy_type gets no
ProtoElemJson impl, so only vtable reflection or reflection with
message cleanup requires it to be local.
§Example
buffa_build::Config::new()
.use_bytes_type_in(&["."]) // all bytes fields use Bytes
.files(&["proto/my_service.proto"])
.includes(&["proto/"])
.compile()
.unwrap();Sourcepub fn use_bytes_type(self) -> Self
pub fn use_bytes_type(self) -> Self
Use bytes::Bytes for all bytes fields in all messages.
This is a convenience for .use_bytes_type_in(&["."]). Use
use_bytes_type_in with specific proto paths if you only want Bytes
for certain fields. See that method for the path-matching semantics, the
map<K, bytes> rule, and the map<bytes, bytes> carve-out under
strict_utf8_mapping.
Sourcepub fn bytes_type_in(self, repr: BytesRepr, paths: &[impl AsRef<str>]) -> Self
pub fn bytes_type_in(self, repr: BytesRepr, paths: &[impl AsRef<str>]) -> Self
Map bytes fields to a BytesRepr other than Vec<u8> for the given
proto path prefixes. The bytes counterpart to
string_type_in.
Each path is a fully-qualified proto path prefix: a field
(".my.pkg.Msg.data"), a message, a package, or "." for every field.
A leading dot is added to each path if missing, surrounding whitespace
and trailing dots are ignored, and a blank entry is skipped with a
cargo:warning.
A rule whose path does not match a field of any type in a generated
message produces a cargo:warning
(CodeGenWarning::FieldTypeRuleMatchedNothing).
A path that matches only fields of another type does not warn.
Rules accumulate and the last matching rule wins, so call the broad
bytes_type first, then bytes_type_in for
narrower overrides. For BytesRepr::Custom, the downstream crate must
depend on the crate providing the type (buffa does not re-export it).
Only the owned Rust type changes — the wire format is unchanged and view
types still borrow &[u8].
Sourcepub fn bytes_type(self, repr: BytesRepr) -> Self
pub fn bytes_type(self, repr: BytesRepr) -> Self
Map every bytes field in all messages to the given BytesRepr.
Convenience for .bytes_type_in(repr, &["."]); call before any
bytes_type_in overrides (last matching rule
wins).
Sourcepub fn bytes_type_custom_in(self, path: &str, paths: &[impl AsRef<str>]) -> Self
pub fn bytes_type_custom_in(self, path: &str, paths: &[impl AsRef<str>]) -> Self
Map the matching bytes fields to a custom type named by its
fully-qualified Rust path (e.g. "::my_crate::MyBytes"). The type must
satisfy buffa::ProtoBytes, and the downstream crate must depend on the
crate providing it. Shorthand for
bytes_type_in(BytesRepr::Custom(path), paths).
§Limitations
- A foreign custom type used as a
repeatedelement — or amap<K, bytes>value — fails to compile under JSON, vtable reflection or reflection with message cleanup: codegen emitsProtoElemJson/ReflectElement/InspectElementimpls for it, which the orphan rule forbids for a foreign type. Wrap it in a crate-local newtype, or useemit_custom_type_impls(false)when the defining crate supplies those integrations. Singular / optional / oneof uses work directly. A type listed withjson_policy_typegets noProtoElemJsonimpl, so only vtable reflection or reflection with message cleanup requires it to be local. - A
Customrule does apply tomap<K, bytes>values (honored like the built-inBytesRepr::Bytes); only themap<bytes, bytes>carve-out keepsVec<u8>values. - A
paththat is not a Rust type path likecrate::Name(for example_,()or&'static [u8]) is reported as a codegen error fromcompile. Associated-type projections and parenthesized type paths are supported. - A custom bytes type needs no native
arbitrary::Arbitraryimpl (a generic builder handles it undergenerate_arbitrary).
Sourcepub fn bytes_type_custom(self, path: &str) -> Self
pub fn bytes_type_custom(self, path: &str) -> Self
Map every bytes field to the given custom type path. Convenience for
.bytes_type_custom_in(path, &["."]); see it for the limitations
(foreign repeated elements, map values, path parsing).
Sourcepub fn unbox_oneof_in(self, paths: &[impl AsRef<str>]) -> Self
pub fn unbox_oneof_in(self, paths: &[impl AsRef<str>]) -> Self
Store the matching message-typed oneof variants inline instead of
wrapping them in Box<T>.
By default every message/group oneof variant is boxed so that recursive
types compile. For non-recursive variants the Box is pure overhead (an
allocation per construction); this opts the matching variants out.
This affects the owned message enum only — view oneof variants remain
boxed.
Each path is a fully-qualified proto variant path prefix, e.g.
".my.pkg.MyMessage.body.small" for one variant or ".my.pkg" for a
package (same matching as use_bytes_type_in).
Paths are normalized as for bytes_type_in. A
rule that matches no variant is not reported.
Recursive variants cannot be stored inline (the type would be
unsized). A rule that names a recursive variant exactly is rejected
at codegen time; a broader prefix rule silently keeps recursive
variants boxed and inlines the rest. For example, with
unbox_oneof_in(&[".my.pkg.Node"]), a self-referential
Node.kind.child variant stays boxed while Node’s other message
variants become inline.
Sourcepub fn unbox_oneof(self) -> Self
pub fn unbox_oneof(self) -> Self
Store every non-recursive message-typed oneof variant inline instead of
boxing it. Convenience for .unbox_oneof_in(&["."]); recursive
variants stay boxed.
Sourcepub fn string_type_in(self, repr: StringRepr, paths: &[impl AsRef<str>]) -> Self
pub fn string_type_in(self, repr: StringRepr, paths: &[impl AsRef<str>]) -> Self
Map string fields to a StringRepr other than String for the
given proto path prefixes. The string counterpart to
use_bytes_type_in.
Each path is a fully-qualified proto path prefix (e.g.
".my.pkg.MyMessage.name" for one field, ".my.pkg" for a package).
Rules accumulate and the last matching rule wins. Order therefore
matters: call string_type (the broad default)
first, then string_type_in for narrower overrides — a broad rule
added after a specific one will shadow it.
For StringRepr::Custom, the type must implement buffa::ProtoString,
and the downstream crate must depend on the crate providing it (buffa does
not re-export it). A foreign type cannot implement ProtoString directly
(orphan rule) — point at a local newtype, or the buffa-smolstr crate for
smol_str::SmolStr.
Only the owned Rust type changes: the wire format is unchanged and view
types still borrow &str. A rule that matches a map field applies to
its string key and its string value.
Path normalization and the warning for a rule that matches nothing are
as described on bytes_type_in.
§Example
buffa_build::Config::new()
.string_type_custom("::buffa_smolstr::SmolStr") // broad default first
.string_type_custom_in("::my_crate::CompactStr", &[".my.pkg.Msg.body"]) // narrow override
.files(&["proto/my_service.proto"])
.includes(&["proto/"])
.compile()
.unwrap();Sourcepub fn string_type(self, repr: StringRepr) -> Self
pub fn string_type(self, repr: StringRepr) -> Self
Map every string field in all messages to the given StringRepr.
Convenience for .string_type_in(repr, &["."]). Call this before any
string_type_in overrides, since the last
matching rule wins (a "." rule added later shadows earlier specific
rules). The rule also covers the string keys and values of map
fields.
Sourcepub fn string_type_custom_in(
self,
path: &str,
paths: &[impl AsRef<str>],
) -> Self
pub fn string_type_custom_in( self, path: &str, paths: &[impl AsRef<str>], ) -> Self
Map the matching string fields to a custom type that implements
buffa::ProtoString, named by its fully-qualified Rust path (e.g.
"::buffa_smolstr::SmolStr", or a local newtype — a foreign type cannot
implement the trait directly). The downstream crate must depend on the
crate providing it. Shorthand for
string_type_in(StringRepr::Custom(path), paths).
§Limitations
- Under vtable reflection (
reflect_modewithReflectMode::VTable), or any reflection with message cleanup, a foreign custom type used as arepeatedelement or as amapkey or value fails to compile: codegen emits aReflectElement,InspectElementorReflectMapKeyimpl for it, which the orphan rule forbids for a foreign type. Wrap it in a crate-local newtype, or useemit_custom_type_impls(false)when the defining crate supplies those integrations. Singular / optional / oneof uses work directly. - JSON of a custom string with explicit presence (proto3 or proto2
optional, and the edition 2023 default), in arepeatedfield, in a oneof, or in amap, serializes through the type’s ownserdeimpls, so such a type must implementSerialize/Deserialize. Abuffa-remote-derivenewtype gets them from#[buffa(remote = ..., serde)]; any other type derives them (an external type enables itsserdefeature). A singular field with implicit presence, or a proto2requiredfield, uses theproto_stringwith-module and needs noserdeimpl, and so does a type listed withjson_policy_type, whose JSON goes through its policy in every generated JSON position. - A custom type used as a
mapkey must implementHash + Eqfor the defaultHashMapcontainer, orOrdforBTreeMap. - A
paththat is not a Rust type path likecrate::Name(for example_,()or&'static [u8]) is reported as a codegen error fromcompile. Associated-type projections and parenthesized type paths are supported. - A custom string type needs no native
arbitrary::Arbitraryimpl (a generic builder handles it undergenerate_arbitrary, as amapkey or value too).
Sourcepub fn json_policy_type(self, path: &str) -> Self
pub fn json_policy_type(self, path: &str) -> Self
Route the protobuf JSON of a custom bytes or string representation
through its buffa::json_helpers::ProtoBytesJson or ProtoStringJson
impl.
path names the type exactly as its
bytes_type_custom_in or
string_type_custom_in rule does
(whitespace aside). Every field of that type then serializes and
deserializes through the policy in the generated serde impls:
singular, optional, repeated and oneof fields, map keys and values,
and the matching fields of generated views, lazy views and owned views.
The type’s own serde impls are not consulted.
Generated code implements no JSON trait for the type (repeated elements
and map values go through buffa’s policy with-modules). With JSON
alone, the type may therefore be defined, together with its
representation and policy impls, in another crate, and separate
compile() runs into one crate may share it. With vtable reflection,
or reflection with message cleanup, its repeated and map uses still
get per-run element impls, so there it must be crate-local and
generated in one run (or use
emit_custom_type_impls(false)). Call
it once per type, in every Config that generates a field of the type:
a run that does not list it never calls the policy (bytes fields become
plain base64; string fields use the type’s own serde impls). Unlisted
custom types keep their existing JSON behavior.
A policy shapes only the generated JSON and is not a confidentiality
boundary. Binary encoding, generated text format and descriptor-driven
reflection never call it: JSON produced or read through DynamicMessage
(including a message converted with ReflectMessage::to_dynamic, or with
DynamicMessage::try_from_message, which works whether or not
reflection is generated) encodes the field as standard base64 or a
plain string, so a policy that refuses export does not stop it and its
import checks do not run.
§Limitations
- The type must implement the policy trait; a missing impl is a compile error in the generated code, naming the trait.
- A listed
stringtype used as the key of amapwith enum values is a codegen error fromcompile. - A listed
stringtype used as amapkey must have a policy that round-trips, and so is injective (see theProtoStringJsoncontract): otherwise import loses or alters entries. This is not checked. - A type that no effective representation rule selects is an error.
Binding and spelling errors remain errors with JSON disabled. A valid
listed type while
generate_jsonis off produces acargo:warningbecause its policy is inactive. - With JSON and reflection both on
(
generate_reflection, or anyreflect_modeother than off), listing any type produces onecargo:warningpercompile()that reflective JSON bypasses the policy. It is a standing reminder, not a check of your schema, and buffa-build always prints it.
Sourcepub fn emit_custom_type_impls(self, enabled: bool) -> Self
pub fn emit_custom_type_impls(self, enabled: bool) -> Self
Control emission of custom bytes/string element integration impls.
Set this to false when shared representation types provide their
ProtoElemJson, ReflectElement, ReflectMapKey and InspectElement implementations in
their defining crate. A type listed with
json_policy_type needs no ProtoElemJson.
This permits foreign types and multiple generation calls without
orphan-rule or duplicate-impl errors. Missing traits fail
compilation; JSON policy selection is still required separately.
Sourcepub fn allow_unmatched_message_rules(self, enabled: bool) -> Self
pub fn allow_unmatched_message_rules(self, enabled: bool) -> Self
Permit global message selectors absent from a scoped generation request. Unmatched selectors still warn. Validate the complete project with this disabled to catch misspelled cleanup or view-export rules as errors.
Sourcepub fn string_type_custom(self, path: &str) -> Self
pub fn string_type_custom(self, path: &str) -> Self
Map every string field to the given custom type path. Convenience for
.string_type_custom_in(path, &["."]); see it for the limitations.
Sourcepub fn map_type_in(self, repr: MapRepr, paths: &[impl AsRef<str>]) -> Self
pub fn map_type_in(self, repr: MapRepr, paths: &[impl AsRef<str>]) -> Self
Map the matching map fields to a MapRepr other than the default
HashMap. Rules are matched with proto-segment-aware prefix logic; the
last matching rule wins, so add a broad rule first and narrower
overrides after.
Path normalization and the warning for a rule that matches nothing are
as described on bytes_type_in.
Use MapRepr::BTreeMap for the buffa-provided BTreeMap (deterministic
key order, no extra dependency, no consumer code), or
MapRepr::Custom for a crate-local newtype that implements
buffa::map_codec::MapStorage.
Only the owned collection changes: the wire format is unchanged and view types are unaffected.
§Example
buffa_build::Config::new()
.map_type(buffa_build::MapRepr::BTreeMap) // broad default
.map_type_in(buffa_build::MapRepr::HashMap, &[".my.pkg.Msg.cache"]) // narrow override
.compile()
.unwrap();Sourcepub fn map_type(self, repr: MapRepr) -> Self
pub fn map_type(self, repr: MapRepr) -> Self
Map every map field in all messages to the given MapRepr.
Convenience for .map_type_in(repr, &["."]). Call this before any
map_type_in overrides, since the last matching
rule wins.
Sourcepub fn map_entries_omit_defaults(self, enabled: bool) -> Self
pub fn map_entries_omit_defaults(self, enabled: bool) -> Self
Encode map entries as prost does: leave an entry’s key or value out when it holds the default (default: false, both are always written, as the C++ and Java runtimes write them). Entries themselves are never dropped.
For migrations from prost where stored or hashed map encodings must
not change. Decoding is unchanged: buffa, like every protobuf runtime,
reads both forms to the same map. One value does not survive the round
trip: a -0.0 float value is left out, as prost leaves it out, and
decodes as 0.0.
The default is what a missing field decodes to: zero, false, empty,
an open enum’s 0 or a closed enum’s first value. A message value is
left out when it encodes to nothing.
§Differences from prost
- prost leaves out a message value equal to its default. A value that
equals its default and still encodes a field, such as one with a
requiredfield at its default or a float field holding-0.0, is written here and not by prost. - A value of an enum made open with
open_enums_inis left out at 0, which a missing open enum decodes to, where prost leaves out the enum’s first value. The two differ only for an enum whose first value is not 0. protoc rejects that as a map value, so the case can occur only with a descriptor set that another tool built (use_buf,descriptor_set). - The option covers the entries’ bytes only. For a map with more than
one entry to encode identically, the entries must also come in the
same order: use
map_typewithMapRepr::BTreeMapwhere prost usedbtree_map.
§Scope
- The option applies to the owned, view and lazy view encoders of the messages generated in this run. Each crate’s types encode as that crate was generated.
google.protobuf.Struct, the well-known type with a map field, comes frombuffa-typesand writes both fields, and so doesDynamicMessage.- A lazy view keeps its singular and repeated message fields undecoded and writes them as they were read, so map entries inside them keep the encoding they arrived with. Every encoder writes entries kept as unknown fields as they were read.
- With
CodecStrategy::Table, messages with a map field keep the unrolled codec, and acodec_strategy_inrule that selects the table for such a message by its exact path is an error.
Sourcepub fn map_type_custom_in(self, path: &str, paths: &[impl AsRef<str>]) -> Self
pub fn map_type_custom_in(self, path: &str, paths: &[impl AsRef<str>]) -> Self
Map the matching map fields to a custom collection implementing
buffa::map_codec::MapStorage, named by its fully-qualified Rust path
(e.g. "::my_crate::OrderedMap"). The path must not include the
<K, V> parameters — they are applied positionally. Shorthand for
map_type_in(MapRepr::Custom(path), paths).
§Limitations
- The path must name a crate-local newtype — a foreign map cannot
implement the buffa-owned reflection / serde traits (orphan rule).
Prefer the built-in
MapRepr::BTreeMapunless you need a specific foreign map. - The newtype must implement
buffa::MapStorageplus the derive /FromIterator/ReflectMap/ serde /arbitrarybounds documented onbuffa::map_codec::MapStorage(the canonical list). JSON andarbitrarywork for every proto map key/value type regardless of the container. - A path that does not parse as a Rust type is reported as a codegen
error from
compile.
Sourcepub fn map_type_custom(self, path: &str) -> Self
pub fn map_type_custom(self, path: &str) -> Self
Map every map field to the given custom collection path. Convenience
for .map_type_custom_in(path, &["."]); see it for the limitations (the
crate-local newtype requirement, the trait bounds, path parsing).
Sourcepub fn box_type_in(self, repr: PointerRepr, paths: &[impl AsRef<str>]) -> Self
pub fn box_type_in(self, repr: PointerRepr, paths: &[impl AsRef<str>]) -> Self
Map the matching message fields to a PointerRepr other than the
default Inline. Rules are matched with proto-segment-aware prefix
logic; the last matching rule wins, so add a broad rule first and
narrower overrides after.
Paths are normalized as for bytes_type_in. A
rule that matches no field is not reported.
The default Inline is recursion-aware (recursive fields stay on
Box), so this knob is for opting out: PointerRepr::Box for large
or rarely-set submessages where reserving size_of::<T>() in the parent
is wasteful, or PointerRepr::Custom for a third-party pointer.
Applies to singular (and proto2 optional/required) message fields and to
boxed oneof message/group variants (matched by the variant’s path).
A oneof variant opted into inline storage via unbox_oneof_in
takes precedence and gets no pointer; recursive variants stay boxed and so
accept a custom pointer. Repeated message fields use a collection, not a
pointer. For PointerRepr::Custom, the pointer must implement
buffa::ProtoBox<T> and be a crate-local newtype; the path is a
template with a * placeholder for the message type (e.g.
"::my_crate::SmallBox<*>").
Only the in-memory pointer changes: the wire format is unchanged and view types are unaffected.
Sourcepub fn codec_strategy(self, strategy: CodecStrategy) -> Self
pub fn codec_strategy(self, strategy: CodecStrategy) -> Self
Choose how the binary Message implementation of every message is
generated (default: CodecStrategy::Unrolled).
On a large schema, CodecStrategy::Table makes the compiled code
about 40% smaller at opt-level = "z", and it slows messages made of
many small fields; a message that cannot use it keeps its size.
CodecStrategy::Table says which messages stay unrolled and how a
table message behaves differently, and this build reports the messages
that stay unrolled in one cargo:warning. The option never changes the
wire format. The generated code needs Rust 1.77 or later, and compile
returns an error on an older compiler when a build script runs it (the
compiler is read from RUSTC).
Path-scoped rules for individual messages go in
codec_strategy_in, and take precedence
over this setting whatever the call order.
// build.rs
buffa_build::Config::new()
.files(&["proto/wa.proto"])
.includes(&["proto/"])
.codec_strategy(buffa_build::CodecStrategy::Table)
.codec_strategy_in(buffa_build::CodecStrategy::Unrolled, &[".wa.Message"])
.compile()?;Sourcepub fn codec_strategy_in(
self,
strategy: CodecStrategy,
paths: &[impl AsRef<str>],
) -> Self
pub fn codec_strategy_in( self, strategy: CodecStrategy, paths: &[impl AsRef<str>], ) -> Self
Choose the CodecStrategy of the matching messages, on top of the
global codec_strategy.
Each path is a fully-qualified proto path prefix, e.g. ".wa.Message"
for one message or ".wa" for a package (same matching as
preserve_unknown_fields_in);
"." matches every message. A leading dot is added if missing,
trailing dots are trimmed, and a path that is empty after that prints a
cargo:warning and is ignored. A rule covers the message it names
and every message nested inside it. The last matching rule wins,
so call this after any broader rule.
A message selected for the table by a rule that cannot use it stays unrolled and is counted in the warning, and it is an error if the rule names the message by its exact path. A rule that matches no message produces a warning.
A rule does not extend to the messages a message holds; see
CodecStrategy::Table.
Sourcepub fn box_type(self, repr: PointerRepr) -> Self
pub fn box_type(self, repr: PointerRepr) -> Self
Map every message field (and boxed oneof variant) to the given PointerRepr.
Convenience for .box_type_in(repr, &["."]). Call before any
box_type_in overrides, since the last matching
rule wins. box_type(PointerRepr::Box) restores the pre-0.9 boxed
default for every singular message field.
Sourcepub fn box_type_custom_in(
self,
template: &str,
paths: &[impl AsRef<str>],
) -> Self
pub fn box_type_custom_in( self, template: &str, paths: &[impl AsRef<str>], ) -> Self
Map the matching singular message fields to a custom pointer implementing
buffa::ProtoBox<T>, named by a Rust type-path template with a *
placeholder for the message type (e.g. "::my_crate::SmallBox<*>").
Shorthand for
box_type_in(PointerRepr::Custom(template), paths).
§Limitations
- The template must contain at least one
*; a template that omits it, or whose substitution does not parse as a Rust type, is reported as a codegen error fromcompile. - The pointer must be exclusively owned (
Rc/Arcare unusable — the decoder needsDerefMut) and a crate-local newtype (a foreign pointer cannot implement the buffa-ownedProtoBox).
Sourcepub fn box_type_custom(self, template: &str) -> Self
pub fn box_type_custom(self, template: &str) -> Self
Map every message field (and boxed oneof variant) to the given custom pointer template.
Convenience for .box_type_custom_in(template, &["."]); see it for the
limitations (the * placeholder, Rc/Arc exclusion, newtype rule).
Sourcepub fn repeated_type_in(
self,
repr: RepeatedRepr,
paths: &[impl AsRef<str>],
) -> Self
pub fn repeated_type_in( self, repr: RepeatedRepr, paths: &[impl AsRef<str>], ) -> Self
Map the matching repeated fields to a RepeatedRepr other than the
default Vec<T>. Rules are matched with proto-segment-aware prefix
logic; the last matching rule wins, so add a broad rule first and
narrower overrides after. Applies only to repeated fields (not map).
Path normalization and the warning for a rule that matches nothing are
as described on bytes_type_in.
For RepeatedRepr::Custom, the collection must implement
buffa::ProtoList<T>. Unlike the scalar string_type_custom /
bytes_type_custom knobs (which take a complete type path), this path
is a template with a * placeholder for the element type. Existing
ProtoList implementations work through aliases and associated types.
If the defining crate provides no implementation, use a crate-local
newtype to satisfy the orphan rule. See RepeatedRepr::Custom for
the bounds required by JSON, reflection and arbitrary generation.
Only the owned collection changes: the wire format is unchanged and view
types still borrow &[T].
§Example
// `SmallList<T>` is a crate-local newtype over smallvec::SmallVec that
// implements buffa::ProtoList (see the ProtoList docs for the template).
buffa_build::Config::new()
.repeated_type_custom("::my_crate::SmallList<*>") // broad default
.repeated_type_custom_in("::my_crate::SmallList8<*>", &[".my.pkg.Msg.tags"])
.compile()
.unwrap();Sourcepub fn repeated_type(self, repr: RepeatedRepr) -> Self
pub fn repeated_type(self, repr: RepeatedRepr) -> Self
Map every repeated field in all messages to the given
RepeatedRepr. Convenience for .repeated_type_in(repr, &["."]).
Call this before any repeated_type_in
overrides, since the last matching rule wins.
Sourcepub fn repeated_type_custom_in(
self,
template: &str,
paths: &[impl AsRef<str>],
) -> Self
pub fn repeated_type_custom_in( self, template: &str, paths: &[impl AsRef<str>], ) -> Self
Map the matching repeated fields to a custom collection implementing
buffa::ProtoList<T>, named by a Rust type-path template with a *
placeholder for the element type (e.g. "::my_crate::SmallList<*>").
Note the asymmetry with the scalar string_type_custom /
bytes_type_custom knobs: those take a complete path, this takes a
*-template that wraps the element. Shorthand for
repeated_type_in(RepeatedRepr::Custom(template), paths).
§Limitations
- The template must contain at least one
*; a template that omits it, or whose substitution is not a Rust type path, is reported as a codegen error fromcompile. - The resolved collection must implement
buffa::ProtoList<T>. An associated type resolving toVec<T>already satisfies this; a foreign collection without an implementation needs a crate-local newtype to satisfy the orphan rule. - Vtable reflection requires
ReflectList; cleanup-profile borrowed inspection requiresInspectList. Ordinary bridge reflection needs neither on the owned collection. - JSON scalar, enum and policy helpers decode through
ProtoList<T>and the element’s JSON traits, without requiring the collection’sDeserialize. Positions using ordinary serde instead require the collection’sSerialize/Deserialize. SeeRepeatedRepr::Customfor the complete representation requirements andbuffa::ProtoListfor a worked newtype example.
Sourcepub fn repeated_type_custom(self, template: &str) -> Self
pub fn repeated_type_custom(self, template: &str) -> Self
Map every repeated field to the given custom collection template.
Convenience for .repeated_type_custom_in(template, &["."]); see it for
the limitations (the * placeholder, foreign reflection, the JSON /
arbitrary requirements).
Sourcepub fn type_attribute(
self,
path: impl Into<String>,
attribute: impl Into<String>,
) -> Self
pub fn type_attribute( self, path: impl Into<String>, attribute: impl Into<String>, ) -> Self
Add a custom attribute to generated types (messages and enums) matching a proto path prefix.
path is a fully-qualified proto path prefix: "." applies to all
types, ".my.pkg" to types in that package, ".my.pkg.MyMessage"
to a specific type. A leading . is auto-prepended if omitted; a
trailing . is trimmed. Prefix matching respects proto-segment
boundaries, so ".my.pk" does not match ".my.pkg.Msg".
attribute is one or more outer Rust attributes, each written with
its #[...] (e.g., "#[derive(serde::Serialize)]"). Any other
string, such as "serde(skip)" or an empty one, makes
compile fail with
CodeGenError::InvalidCustomAttribute,
whether or not path matches a generated type.
Multiple calls accumulate in insertion order — all matching attributes are emitted, and ordering is preserved in generated code.
Also applies to generated oneof enums when path matches
".pkg.Msg.my_oneof" (the oneof’s fully-qualified path).
§Pitfalls
buffa already emits #[derive(Clone, PartialEq)] on messages and
#[derive(Clone, PartialEq, Debug)] on oneofs (oneofs with a
[debug_redact = true] variant get a generated Debug impl instead
of the Debug derive); adding a duplicate derive via
type_attribute(".", "#[derive(Clone)]") produces a compile error in
the generated code.
A custom serde::Serialize derive has two additional requirements:
messages must disable unknown-field preservation because
UnknownFields does not implement serde::Serialize, and the json
feature must be enabled for buffa’s EnumValue and MessageField
serde implementations. Do not combine a custom derive with
generate_json(true), which already generates
the message’s serde implementations.
§Example
buffa_build::Config::new()
// `UnknownFields` does not implement `serde::Serialize`; with this
// off, unknown fields are dropped on decode.
.preserve_unknown_fields(false)
.type_attribute(".", "#[derive(serde::Serialize)]")
.type_attribute(".my.pkg.MyEnum", "#[derive(strum::EnumIter)]")
.files(&["proto/my_service.proto"])
.includes(&["proto/"])
.compile()
.unwrap();Sourcepub fn field_attribute(
self,
path: impl Into<String>,
attribute: impl Into<String>,
) -> Self
pub fn field_attribute( self, path: impl Into<String>, attribute: impl Into<String>, ) -> Self
Add a custom attribute to generated struct fields matching a proto path prefix.
path is a fully-qualified proto field path (e.g.,
".my.pkg.MyMessage.my_field"). "." applies to all fields. A
leading . is auto-prepended if omitted; a trailing . is trimmed.
Prefix matching respects proto-segment boundaries.
Also applies to oneof variants when path matches
".pkg.Msg.my_oneof.variant_name", but not to the struct field holding
the oneof; use
oneof_struct_field_attribute for
that.
attribute follows the rule given for
type_attribute: any string that is not one
or more #[...] attributes, an empty one included, makes
compile fail.
A #[deprecated] supplied here wins over the one codegen derives from
the field’s [deprecated = true] option — rustc permits only one
deprecated attribute per item — so this is also how to attach a note
naming the replacement. Either source marks every generated way to
reach a message field: the with_* setter, the same field on the
views, its OwnedView accessor and, for a required field, the views’
has_* method. Those carry a bare #[deprecated]; the attribute given
here, with its note, stays on the owned struct’s field. Either source
also makes the generated items that visit the field carry
#[allow(deprecated)].
A deprecated inside cfg_attr counts too: it replaces the
option-derived marker on the owned field, and the setter and view
markers stay unconditional.
A oneof variant gets only the attribute given here. Its view variant is
unmarked and the generated impls that match on it are not guarded, so
put #[allow(deprecated)] on the mod that includes the generated
file.
§Example
buffa_build::Config::new()
.field_attribute(".my.pkg.MyMessage.secret_key", "#[serde(skip)]")
.files(&["proto/my_service.proto"])
.includes(&["proto/"])
.compile()
.unwrap();Sourcepub fn message_attribute(
self,
path: impl Into<String>,
attribute: impl Into<String>,
) -> Self
pub fn message_attribute( self, path: impl Into<String>, attribute: impl Into<String>, ) -> Self
Add a custom attribute to generated message structs only (not enums,
not oneof enums — those are reached by
enum_attribute and
oneof_attribute respectively) matching a
proto path prefix.
Same path-matching semantics as type_attribute —
leading . auto-prepended, trailing . trimmed, proto-segment-aware
prefix matching, accumulation in insertion order. Useful for
struct-only attributes like #[serde(default)].
attribute follows the rule given for
type_attribute: any string that is not one
or more #[...] attributes, an empty one included, makes
compile fail.
§Example
buffa_build::Config::new()
.message_attribute(".", "#[serde(default)]")
.files(&["proto/my_service.proto"])
.includes(&["proto/"])
.compile()
.unwrap();Sourcepub fn enum_attribute(
self,
path: impl Into<String>,
attribute: impl Into<String>,
) -> Self
pub fn enum_attribute( self, path: impl Into<String>, attribute: impl Into<String>, ) -> Self
Add a custom attribute to generated enum types only (not message
structs, not oneof enums — those are reached by
type_attribute on the oneof’s path or by
oneof_attribute) matching a proto path
prefix.
Same path-matching semantics as type_attribute —
leading . auto-prepended, trailing . trimmed, proto-segment-aware
prefix matching, accumulation in insertion order. Useful when you want
to inject an attribute on every enum in a package without also matching
the (often more numerous) messages that share the path prefix — e.g.
#[derive(strum::EnumIter)], which only makes sense on enums.
attribute follows the rule given for
type_attribute: any string that is not one
or more #[...] attributes, an empty one included, makes
compile fail.
§Example
buffa_build::Config::new()
.enum_attribute(".my.pkg", "#[derive(strum::EnumIter)]")
.files(&["proto/my_service.proto"])
.includes(&["proto/"])
.compile()
.unwrap();Sourcepub fn oneof_attribute(
self,
path: impl Into<String>,
attribute: impl Into<String>,
) -> Self
pub fn oneof_attribute( self, path: impl Into<String>, attribute: impl Into<String>, ) -> Self
Add a custom attribute to generated oneof enums only (not message structs, not regular enums) matching a proto path prefix.
Same path-matching semantics as type_attribute:
a leading . is auto-prepended, a trailing . is trimmed, prefixes
match on proto-path segments, and attributes accumulate in insertion
order. The match key is the oneof’s fully-qualified path
(.my.pkg.MyMessage.my_oneof) — the whole-enum path has no variant
segment; to target a single variant’s field, append .variant_name
and use field_attribute instead, and for the
message struct’s field holding the oneof, use
oneof_struct_field_attribute.
attribute follows the rule given for
type_attribute: any string that is not one
or more #[...] attributes, an empty one included, makes
compile fail.
Useful when a oneof needs a different attribute set than the
surrounding types — for example to keep #[derive(serde::Serialize)]
on messages and oneofs while
enum_attribute gives the regular enums a
different serde derive.
Applies to the owned oneof enum only; the zero-copy view-of-oneof
enum receives no custom attributes (true of the whole attribute
family). For JSON serialization of both owned types and views, use
generate_json(true), which emits canonical
protobuf-JSON impls rather than derived ones.
§Pitfalls
Generated oneof enums already derive Clone, PartialEq, and
Debug (oneofs containing [debug_redact = true] fields replace the
Debug derive with a manual impl). Re-deriving any of these via
oneof_attribute produces a conflicting-implementation compile error
inside the generated code.
For the serde::Serialize requirements when the surrounding messages
also use a custom derive, see the type_attribute
pitfalls: disable unknown-field preservation for messages and enable
the json feature for buffa’s serde implementations. Do not combine
custom derives with generate_json(true).
§Example
buffa_build::Config::new()
// one specific oneof; ".my.pkg" would match every oneof in the package
.oneof_attribute(".my.pkg.MyMessage.my_oneof", "#[derive(serde::Serialize)]")
.files(&["proto/my_service.proto"])
.includes(&["proto/"])
.compile()
.unwrap();Sourcepub fn oneof_struct_field_attribute(
self,
path: impl Into<String>,
attribute: impl Into<String>,
) -> Self
pub fn oneof_struct_field_attribute( self, path: impl Into<String>, attribute: impl Into<String>, ) -> Self
Add a custom attribute to the message struct’s field holding a oneof
(the Option<OneofEnum> member), not to the oneof’s variants.
The match key is the oneof’s fully-qualified path
(.my.pkg.MyMessage.my_oneof), with the same path-matching semantics
as type_attribute: ".my.pkg" reaches the
oneof field of every message in the package, nested ones included.
Attributes accumulate in insertion order, after buffa’s own attributes
on the field.
attribute follows the rule given for
type_attribute: any string that is not one
or more #[...] attributes, an empty one included, makes
compile fail.
A rule on a variant’s path (.my.pkg.MyMessage.my_oneof.variant_name)
does not match the oneof, so it has no effect, and the build does not
warn about it. Variants take their attributes from
field_attribute.
Each of these lines of the generated code for a oneof takes its attributes from a different method:
pub struct Event {
// oneof_struct_field_attribute(".pkg.Event.payload", ..)
pub payload: Option<event::Payload>,
}
// oneof_attribute(".pkg.Event.payload", ..), or type_attribute on the same path
pub enum Payload {
// field_attribute(".pkg.Event.payload.text", ..)
Text(String),
}field_attribute on the oneof’s path (.pkg.Event.payload) matches
the variants only, where an attribute
such as #[serde(skip_serializing_if = "...")] is rejected. prost-build
puts such a field_attribute on the struct field as well; use this
method for the struct field.
Applies to the owned message struct only; the view structs do not get the attribute.
A #[deprecated] given here marks the owned struct’s field only. The
same field on the view structs stays unmarked, so reading the oneof
through a view does not warn, unlike a field deprecated through
field_attribute. The generated items that visit the owned field
carry #[allow(deprecated)].
§Pitfalls
With generate_json(true) the field already
carries buffa’s #[serde(flatten)] for the derived Serialize, and
buffa generates the Deserialize impl of a message with a oneof
instead of deriving it. So a serde attribute given here changes the
owned message’s Serialize output only: Deserialize and the views’
Serialize ignore it. A second flatten is a compile error in the
generated code. Serde attributes here are for a serde derive that you
attach yourself, with generate_json off.
With
gate_impls_on_crate_features(true)
buffa’s serde derive is compiled only under the JSON feature. Write a
serde attribute for it as #[cfg_attr(feature = "json", serde(...))],
with your JSON feature’s name if you renamed it, so that it is compiled
under the same feature.
§Example
buffa_build::Config::new()
// `UnknownFields` does not implement `serde::Serialize`. With this
// off, unknown fields are dropped on decode.
.preserve_unknown_fields(false)
.message_attribute(".my.pkg.MyMessage", "#[derive(serde::Serialize)]")
.oneof_attribute(".my.pkg.MyMessage.my_oneof", "#[derive(serde::Serialize)]")
.oneof_struct_field_attribute(
".my.pkg.MyMessage.my_oneof",
"#[serde(skip_serializing_if = \"Option::is_none\")]",
)
.files(&["proto/my_service.proto"])
.includes(&["proto/"])
.compile()
.unwrap();Sourcepub fn use_buf(self) -> Self
pub fn use_buf(self) -> Self
Use buf build instead of protoc for descriptor generation.
buf is often easier to install and keep current than protoc
(which many distros pin to old versions). This mode is intended for
the single-crate case: a buf.yaml at the crate root defining
the module layout.
Requires buf on PATH and a buf.yaml at the crate root. The
includes() setting is ignored — buf resolves
imports via its own module configuration.
Each path given to files() must be relative to its
owning module’s directory (the path: value inside buf.yaml), not
the crate root where buf.yaml itself lives. buf strips the module
path when producing FileDescriptorProto.name, so for
modules: [{path: proto}] and a file on disk at
proto/api/v1/service.proto, the descriptor name is
api/v1/service.proto — that is what .files() must contain.
Multiple modules in one buf.yaml work fine; buf enforces that
module-relative names are unique across the workspace.
§Monorepo / multi-module setups
For a workspace-root buf.yaml with many modules, this mode is a
poor fit. Prefer running buf generate with the protoc-gen-reallyme-buffa
plugin and checking in the generated code, or use
descriptor_set() with the output of
buf build --as-file-descriptor-set -o fds.binpb <module-path>
run as a pre-build step.
§Example
// buf.yaml (at crate root):
// version: v2
// modules:
// - path: proto
//
// build.rs:
buffa_build::Config::new()
.use_buf()
.files(&["api/v1/service.proto"]) // relative to module root
.compile()
.unwrap();Sourcepub fn descriptor_set(self, path: impl Into<PathBuf>) -> Self
pub fn descriptor_set(self, path: impl Into<PathBuf>) -> Self
Use a pre-compiled FileDescriptorSet binary file as input.
Skips invoking protoc or buf entirely. The file must contain a
serialized google.protobuf.FileDescriptorSet (as produced by
protoc --descriptor_set_out or buf build --as-file-descriptor-set).
When using this, .files() specifies which proto files in the
descriptor set to generate code for (matching by proto file name).
For in-memory input, use descriptor_set_bytes().
Sourcepub fn descriptor_set_bytes(self, bytes: Vec<u8>) -> Self
pub fn descriptor_set_bytes(self, bytes: Vec<u8>) -> Self
Use a serialized google.protobuf.FileDescriptorSet held in memory.
Use this when the build script produces the descriptor set itself, for
example with an in-process compiler such as protox.
compile() decodes the bytes and does not invoke
protoc or buf. This replaces any previously configured descriptor
source. Pass a slice as bytes.to_vec().
files() selects which proto files in the descriptor set
to generate, using their exact descriptor names (relative to the proto
source root). The set must also contain their transitive imports.
includes() is ignored.
§Rebuilds
Print a cargo:rerun-if-changed or cargo:rerun-if-env-changed line
for every input the bytes were built from. buffa-build cannot see
those inputs, and compile() always prints a rerun-if-env-changed
line of its own, which turns off Cargo’s default of rerunning the build
script when any file in the package changes. Without your own lines, an
edited .proto file does not rerun the script, and the generated code
goes stale.
§Example
let bytes: Vec<u8> = compile_protos_in_process();
println!("cargo:rerun-if-changed=proto");
buffa_build::Config::new()
.descriptor_set_bytes(bytes)
.files(&["api/v1/service.proto"])
.compile()?;Sourcepub fn include_file(self, name: impl Into<String>) -> Self
pub fn include_file(self, name: impl Into<String>) -> Self
Generate a module-tree include file alongside the per-package .rs
files.
The include file contains nested pub mod declarations with
include!() directives that assemble the generated code into a
module hierarchy matching the protobuf package structure. Users can
then include this single file instead of manually creating the
module tree.
The form of the emitted include! directives depends on whether
out_dir was set:
- Default (
$OUT_DIR): emitsinclude!(concat!(env!("OUT_DIR"), "/foo.rs")), for use frombuild.rsviainclude!(concat!(env!("OUT_DIR"), "/<name>")). - Explicit
out_dir: emits sibling-relativeinclude!("foo.rs"), for checking the generated code into the source tree and referencing it as a module (e.g.mod gen;). The include file then has to sit inout_diritself:namemust be a bare file name, andcompilerejects a name with a directory part.
With shared_descriptor_pool, name
must be a bare file name in both modes. In $OUT_DIR mode without the
shared pool, name may have a directory part ("nested/_include.rs"),
and compile creates that directory.
§Example — build.rs / $OUT_DIR
// build.rs
buffa_build::Config::new()
.files(&["proto/my_service.proto"])
.includes(&["proto/"])
.include_file("_include.rs")
.compile()
.unwrap();
// lib.rs
include!(concat!(env!("OUT_DIR"), "/_include.rs"));§Example — checked-in source
// codegen.rs (run manually, not from build.rs)
buffa_build::Config::new()
.files(&["proto/my_service.proto"])
.includes(&["proto/"])
.out_dir("src/gen")
.include_file("mod.rs")
.compile()
.unwrap();
// lib.rs
mod gen;Sourcepub fn compile(self) -> Result<(), Box<dyn Error>>
pub fn compile(self) -> Result<(), Box<dyn Error>>
Compile proto files and generate Rust source.
§Errors
Returns an error if:
OUT_DIRis not set and noout_dirwas configuredshared_descriptor_poolis set without reflection enabled, withoutinclude_file, or with aninclude_filethat is not a bare file name or lacks a file-name stem- an explicit
out_diris combined with aninclude_filethat is not a bare file name protocorbufcannot be found onPATH(when using those sources)- the proto compiler exits with a non-zero status (syntax errors, missing imports, etc.)
- a precompiled descriptor set file cannot be read
- the descriptor set bytes cannot be decoded as a
FileDescriptorSet - an
extern_pathproto name has an empty segment or a segment that is not a protobuf identifier - a custom attribute string, given to
type_attributeor one of the five methods beside it, is not one or more#[...]attributes - code generation fails (e.g. unsupported proto feature), including a
codec_strategy_inrule that names by its exact path a message that cannot use the table codec CodecStrategy::Tableis requested and the compiler is older than Rust 1.77- the output directory cannot be created or written to