From b5a6127b33767d140b2630cef777a74431cf5ea1 Mon Sep 17 00:00:00 2001 From: g0itb4 <253692991+g0itb4@users.noreply.github.com> Date: Fri, 13 Nov 2026 00:01:05 +1100 Subject: [PATCH] protoc-gen-buffa: add bytes_type and bytes_type_in options `buffa-build` can generate `bytes` fields as `bytes::Bytes` (`bytes_type`, `bytes_type_in`, `use_bytes_type`), which decode from a `Bytes`-backed buffer without a copy. The plugin had no option that sets `CodeGenConfig::bytes_fields`, so a `buf generate` or `protoc` workflow always got `Vec` and copied every `bytes` payload on decode. The plugin now accepts: - `bytes_type=`: a rule for every `bytes` field; - `bytes_type_in==`: repeatable, path-scoped. `` is `vec` or `bytes`. Rules accumulate in option order and the last matching rule wins, as in the builder. The grammar follows `codec_strategy_in`. Custom types (`bytes_type_custom`) and `string_type` stay builder-only: a string has no built-in alternative to `String`, so a string option would only be useful with a Rust path. Tests cover each option, path normalization, rule order, rejected values and malformed rules, and one CLI test checks that `bytes_type=bytes` generates a `::buffa::bytes::Bytes` field. The CLI tests share a `run_plugin` helper that spawns the plugin and decodes its response. The guide lists the options. --- .../added-20261112-plugin-bytes-type.yaml | 4 + docs/guide.md | 4 +- protoc-gen-buffa/src/main.rs | 102 +++++++++++++++++- protoc-gen-buffa/tests/cli.rs | 76 ++++++++++--- 4 files changed, 169 insertions(+), 17 deletions(-) create mode 100644 .changes/unreleased/added-20261112-plugin-bytes-type.yaml diff --git a/.changes/unreleased/added-20261112-plugin-bytes-type.yaml b/.changes/unreleased/added-20261112-plugin-bytes-type.yaml new file mode 100644 index 000000000..d46e6c737 --- /dev/null +++ b/.changes/unreleased/added-20261112-plugin-bytes-type.yaml @@ -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==` 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 diff --git a/docs/guide.md b/docs/guide.md index 10c100a51..ba63ca88c 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -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=` and `bytes_type_in==`, where `` 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 @@ -662,6 +662,8 @@ Passed via `opt:` (works for `remote:` and `local:`): | `codec_strategy_in==` | 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`. Recursive variants stay boxed. | | `unbox_oneof_in=` | Store matching non-recursive message/group oneof variants inline instead of `Box`. 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` values, as `bytes::Bytes`, which decodes without a copy from a `Bytes`-backed buffer (default: `vec`, `Vec`). See [String and bytes field representations](#string-and-bytes-field-representations) | +| `bytes_type_in==` | 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) | diff --git a/protoc-gen-buffa/src/main.rs b/protoc-gen-buffa/src/main.rs index f8668a4b3..f8a4209c0 100644 --- a/protoc-gen-buffa/src/main.rs +++ b/protoc-gen-buffa/src/main.rs @@ -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. @@ -357,6 +357,27 @@ fn parse_config(params: &str) -> Result { .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==`; 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==' \ + (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 @@ -535,6 +556,18 @@ fn parse_codec_strategy(value: &str) -> Result { } } +/// The built-in `bytes` representations. A custom type stays builder-only +/// (`bytes_type_custom`). +fn parse_bytes_repr(value: &str) -> Result { + 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 { match value.trim() { "true" => Ok(true), @@ -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=="), "{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( diff --git a/protoc-gen-buffa/tests/cli.rs b/protoc-gen-buffa/tests/cli.rs index e68bc73c7..2b3c5b069 100644 --- a/protoc-gen-buffa/tests/cli.rs +++ b/protoc-gen-buffa/tests/cli.rs @@ -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(); @@ -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}" + ); +}