Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .changes/unreleased/added-20261112-plugin-bytes-type.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
kind: Added
body: |-
**`protoc-gen-buffa` accepts `bytes_type` and `bytes_type_in` options.** `bytes_type=bytes` generates every `bytes` field as `bytes::Bytes`, and `bytes_type_in=<path>=<repr>` selects `vec` or `bytes` for matching fields, with the rule order of `buffa_build::Config::bytes_type` / `bytes_type_in` (the last matching rule wins). A `buf generate` or `protoc` workflow can now decode `bytes` fields without a copy, as `buffa-build` users already could. Custom bytes types remain builder-only.
time: 2026-11-12T00:00:00+00:00
4 changes: 3 additions & 1 deletion docs/guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -388,7 +388,7 @@ Key points:
- **A custom string used as a `map` key needs `Hash + Eq`** (for the default / `HashMap` container) or `Ord` (for `map_type(BTreeMap)`). The bound is enforced at the generated map field type, so a missing impl is a clear compile error at that field.
- **A custom type used as a `repeated` element, or as a `map` key/value, must be crate-local.** Codegen emits per-element `ReflectElement` (vtable reflection), `ReflectMapKey` (vtable, for a custom `string` map key), and base64 `ProtoElemJson` (JSON, bytes only) impls for it, which the orphan rule forbids for a foreign type — a local newtype satisfies this. Singular / optional / oneof uses have no such restriction.

`string_type` / `bytes_type` are `buffa-build` / `buffa-codegen` options only — there is no `protoc-gen-buffa` plugin equivalent yet.
`protoc-gen-buffa` selects the built-in `bytes` representations with `bytes_type=<repr>` and `bytes_type_in=<path>=<repr>`, where `<repr>` is `vec` or `bytes` (see [Plugin options](#plugin-options)). `string_type` and the custom-type options (`bytes_type_custom`, `string_type_custom`) are `buffa-build` / `buffa-codegen` options only — there is no plugin equivalent yet.

### Multi-package projects

Expand Down Expand Up @@ -662,6 +662,8 @@ Passed via `opt:` (works for `remote:` and `local:`):
| `codec_strategy_in=<path>=<strategy>` | Choose `table` or `unrolled` for matching messages and the messages nested in them. Repeatable; leading dot optional; the last matching rule wins |
| `unbox_oneof=true` | Store every non-recursive message/group oneof variant inline instead of `Box<T>`. Recursive variants stay boxed. |
| `unbox_oneof_in=<path>` | Store matching non-recursive message/group oneof variants inline instead of `Box<T>`. Repeatable; leading dot optional. Use `.` to match all variants. Recursive variants stay boxed for broad matches; exact recursive matches are rejected. |
| `bytes_type=bytes` | Generate every `bytes` field, including `map<K, bytes>` values, as `bytes::Bytes`, which decodes without a copy from a `Bytes`-backed buffer (default: `vec`, `Vec<u8>`). See [String and bytes field representations](#string-and-bytes-field-representations) |
| `bytes_type_in=<path>=<repr>` | Select `vec` or `bytes` for matching `bytes` fields, e.g. `bytes_type_in=.my.pkg.Frame.payload=bytes`. Repeatable; leading dot optional; the last matching rule wins, so put `bytes_type` first. Custom types remain builder-only |
| `reflection=true` | Emit reflection support (vtable mode) plus an embedded per-package descriptor pool — see [Runtime reflection](#runtime-reflection) |
| `reflect_mode=off\|bridge\|vtable` | Finer-grained reflection selector; `reflection=true` is shorthand for `vtable` |
| `shared_descriptor_pool=true` | Deduplicate the embedded descriptor set: per-package reflect modules delegate to one shared `__buffa_fds` root module. Pass a matching `shared_descriptor_pool=true` to `protoc-gen-buffa-packaging` so the root module is emitted. See [Runtime reflection](#runtime-reflection) |
Expand Down
102 changes: 101 additions & 1 deletion protoc-gen-buffa/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use buffa_codegen::generated::compiler::code_generator_response::File as CodeGen
use buffa_codegen::generated::compiler::CodeGeneratorResponse;
use buffa_codegen::generated::descriptor::Edition;

use buffa_codegen::{CodeGenConfig, CodecStrategy, EnumTypeOverride, FeatureOverride};
use buffa_codegen::{BytesRepr, CodeGenConfig, CodecStrategy, EnumTypeOverride, FeatureOverride};

const HELP: &str = "\
protoc-gen-buffa — protoc plugin for generating Rust code with buffa.
Expand Down Expand Up @@ -357,6 +357,27 @@ fn parse_config(params: &str) -> Result<PluginConfig, String> {
.unboxed_oneof_fields
.push(normalize_unbox_oneof_path(value.trim())?);
}
// `bytes_type=bytes` generates every `bytes` field as
// `bytes::Bytes` (default `vec`). Path-scoped rules use the
// repeatable `bytes_type_in=<path>=<repr>`; as in buffa-build's
// `bytes_type` / `bytes_type_in`, rules accumulate in option
// order and the last matching rule wins.
"bytes_type" => codegen
.bytes_fields
.push((".".to_string(), parse_bytes_repr(value)?)),
"bytes_type_in" => {
let (path, repr) = value.rsplit_once('=').ok_or_else(|| {
format!(
"invalid bytes_type_in format '{value}', expected \
'bytes_type_in=<proto_path>=<repr>' \
(e.g. 'bytes_type_in=.my.pkg.Msg.payload=bytes')"
)
})?;
codegen.bytes_fields.push((
normalize_proto_path(path.trim(), "bytes_type_in")?,
parse_bytes_repr(repr)?,
));
}
// `codec_strategy=table` generates the binary `Message` impl of
// each message the table can handle from a static table and shared
// interpreters (default `unrolled`). Path-scoped rules use the repeatable
Expand Down Expand Up @@ -535,6 +556,18 @@ fn parse_codec_strategy(value: &str) -> Result<CodecStrategy, String> {
}
}

/// The built-in `bytes` representations. A custom type stays builder-only
/// (`bytes_type_custom`).
fn parse_bytes_repr(value: &str) -> Result<BytesRepr, String> {
match value.trim() {
"vec" => Ok(BytesRepr::Vec),
"bytes" => Ok(BytesRepr::Bytes),
other => Err(format!(
"invalid bytes type '{other}', expected 'vec' or 'bytes'"
)),
}
}

fn parse_bool(key: &str, value: &str) -> Result<bool, String> {
match value.trim() {
"true" => Ok(true),
Expand Down Expand Up @@ -838,6 +871,73 @@ mod tests {
}
}

#[test]
fn bytes_type_defaults_to_no_rules() {
assert!(parse_config("").unwrap().codegen.bytes_fields.is_empty());
}

#[test]
fn bytes_type_sets_a_rule_for_every_field() {
assert_eq!(
parse_config("bytes_type=bytes")
.unwrap()
.codegen
.bytes_fields,
vec![(".".to_string(), BytesRepr::Bytes)],
);
assert_eq!(
parse_config("bytes_type= vec ")
.unwrap()
.codegen
.bytes_fields,
vec![(".".to_string(), BytesRepr::Vec)],
);
}

#[test]
fn bytes_type_in_is_repeatable_normalized_and_kept_in_order() {
let config = parse_config(
"bytes_type=bytes,bytes_type_in=pkg.Msg.data=vec,\
bytes_type_in= .pkg.Other. =bytes,\
bytes_type_in=.=vec",
)
.unwrap();
assert_eq!(
config.codegen.bytes_fields,
vec![
(".".to_string(), BytesRepr::Bytes),
(".pkg.Msg.data".to_string(), BytesRepr::Vec),
(".pkg.Other".to_string(), BytesRepr::Bytes),
(".".to_string(), BytesRepr::Vec),
],
);
}

#[test]
fn bytes_type_rejects_unknown_representations() {
for params in [
"bytes_type=Bytes",
"bytes_type=::my_crate::MyBytes",
"bytes_type=",
"bytes_type_in=.pkg.Msg.data=custom",
"bytes_type_in=.pkg.Msg.data=",
] {
let err = parse_err(params);
assert!(
err.contains("expected 'vec' or 'bytes'"),
"{params:?}: {err}"
);
}
}

#[test]
fn bytes_type_in_rejects_malformed_rules() {
let err = parse_err("bytes_type_in=.pkg.Msg.data");
assert!(err.contains("bytes_type_in=<proto_path>=<repr>"), "{err}");
let err = parse_err("bytes_type_in==bytes");
assert!(err.contains("non-empty proto path"), "{err}");
}

#[test]
fn codec_strategy_sets_the_global_default_and_rules_are_repeatable() {
let config = parse_config(
Expand Down
76 changes: 61 additions & 15 deletions protoc-gen-buffa/tests/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,31 @@ use std::process::{Command, Stdio};

use buffa::Message;
use buffa_codegen::generated::compiler::{CodeGeneratorRequest, CodeGeneratorResponse};
use buffa_codegen::generated::descriptor::field_descriptor_proto::{Label, Type};
use buffa_codegen::generated::descriptor::{
DescriptorProto, FieldDescriptorProto, FileDescriptorProto,
};

const BIN: &str = env!("CARGO_BIN_EXE_protoc-gen-buffa");

/// Run the plugin on `request` and decode its response. The plugin reports
/// errors in the response, so it must exit successfully either way.
fn run_plugin(request: &CodeGeneratorRequest) -> CodeGeneratorResponse {
let mut input = Vec::new();
request.encode(&mut input);

let mut child = Command::new(BIN)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.unwrap();
child.stdin.as_mut().unwrap().write_all(&input).unwrap();
let out = child.wait_with_output().unwrap();

assert!(out.status.success());
CodeGeneratorResponse::decode_from_slice(&out.stdout).unwrap()
}

#[test]
fn version_prints_name_and_version() {
let out = Command::new(BIN).arg("--version").output().unwrap();
Expand Down Expand Up @@ -46,23 +68,47 @@ fn unrecognized_arg_exits_2() {

#[test]
fn invalid_plugin_option_returns_response_error() {
let request = CodeGeneratorRequest {
let response = run_plugin(&CodeGeneratorRequest {
parameter: Some("unknown_key=value".into()),
..Default::default()
};
let mut input = Vec::new();
request.encode(&mut input);

let mut child = Command::new(BIN)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.unwrap();
child.stdin.as_mut().unwrap().write_all(&input).unwrap();
let out = child.wait_with_output().unwrap();

assert!(out.status.success());
let response = CodeGeneratorResponse::decode_from_slice(&out.stdout).unwrap();
});
let error = response.error.as_deref().unwrap_or_default();
assert!(error.contains("unknown_key"), "error response: {error}");
}

#[test]
fn bytes_type_option_generates_bytes_fields() {
let file = FileDescriptorProto {
name: Some("frame.proto".into()),
package: Some("demo".into()),
syntax: Some("proto3".into()),
message_type: vec![DescriptorProto {
name: Some("Frame".into()),
field: vec![FieldDescriptorProto {
name: Some("payload".into()),
number: Some(1),
label: Some(Label::LABEL_OPTIONAL),
r#type: Some(Type::TYPE_BYTES),
..Default::default()
}],
..Default::default()
}],
..Default::default()
};
let response = run_plugin(&CodeGeneratorRequest {
parameter: Some("bytes_type=bytes".into()),
file_to_generate: vec!["frame.proto".into()],
proto_file: vec![file],
..Default::default()
});
assert_eq!(response.error, None);
let content: String = response
.file
.iter()
.filter_map(|f| f.content.as_deref())
.collect();
assert!(
content.contains("pub payload: ::buffa::bytes::Bytes"),
"generated code: {content}"
);
}
Loading