Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow using Box<[u8]>/Box<str> for bytes/string fields #878

Open
wants to merge 14 commits into
base: master
Choose a base branch
from
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
20 changes: 10 additions & 10 deletions README.md
Expand Up @@ -329,12 +329,12 @@ and the generated Rust code (`tutorial.rs`):
```rust,ignore
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Person {
#[prost(string, tag="1")]
#[prost(string = "string", tag="1")]
pub name: ::prost::alloc::string::String,
/// Unique ID number for this person.
#[prost(int32, tag="2")]
pub id: i32,
#[prost(string, tag="3")]
#[prost(string = "string", tag="3")]
pub email: ::prost::alloc::string::String,
#[prost(message, repeated, tag="4")]
pub phones: ::prost::alloc::vec::Vec<person::PhoneNumber>,
Expand All @@ -343,7 +343,7 @@ pub struct Person {
pub mod person {
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PhoneNumber {
#[prost(string, tag="1")]
#[prost(string = "string", tag="1")]
pub number: ::prost::alloc::string::String,
#[prost(enumeration="PhoneType", tag="2")]
pub r#type: i32,
Expand Down Expand Up @@ -422,15 +422,15 @@ use prost::{Enumeration, Message};

#[derive(Clone, PartialEq, Message)]
struct Person {
#[prost(string, tag = "1")]
#[prost(string = "string", tag = "1")]
pub id: String, // tag=1
// NOTE: Old "name" field has been removed
// pub name: String, // tag=2 (Removed)
#[prost(string, tag = "6")]
#[prost(string = "string", tag = "6")]
pub given_name: String, // tag=6
#[prost(string)]
#[prost(string = "string")]
pub family_name: String, // tag=7
#[prost(string)]
#[prost(string = "string")]
pub formatted_name: String, // tag=8
#[prost(uint32, tag = "3")]
pub age: u32, // tag=3
Expand All @@ -439,11 +439,11 @@ struct Person {
#[prost(enumeration = "Gender")]
pub gender: i32, // tag=5
// NOTE: Skip to less commonly occurring fields
#[prost(string, tag = "16")]
#[prost(string = "string", tag = "16")]
pub name_prefix: String, // tag=16 (eg. mr/mrs/ms)
#[prost(string)]
#[prost(string = "string")]
pub name_suffix: String, // tag=17 (eg. jr/esq)
#[prost(string)]
#[prost(string = "string")]
pub maiden_name: String, // tag=18
}

Expand Down
84 changes: 67 additions & 17 deletions prost-build/src/code_generator.rs
Expand Up @@ -18,7 +18,7 @@ use crate::ast::{Comments, Method, Service};
use crate::extern_paths::ExternPaths;
use crate::ident::{to_snake, to_upper_camel};
use crate::message_graph::MessageGraph;
use crate::{BytesType, Config, MapType};
use crate::{BytesType, Config, MapType, StringType};

#[derive(PartialEq)]
enum Syntax {
Expand Down Expand Up @@ -350,20 +350,9 @@ impl<'a> CodeGenerator<'a> {

self.push_indent();
self.buf.push_str("#[prost(");
let type_tag = self.field_type_tag(&field);
let type_tag = self.field_type_tag_detailed(fq_message_name, &field);
self.buf.push_str(&type_tag);

if type_ == Type::Bytes {
let bytes_type = self
.config
.bytes_type
.get_first_field(fq_message_name, field.name())
.copied()
.unwrap_or_default();
self.buf
.push_str(&format!("={:?}", bytes_type.annotation()));
}

match field.label() {
Label::Optional => {
if optional {
Expand Down Expand Up @@ -566,7 +555,7 @@ impl<'a> CodeGenerator<'a> {
self.path.pop();

self.push_indent();
let ty_tag = self.field_type_tag(&field);
let ty_tag = self.field_type_tag_detailed(fq_message_name, &field);
self.buf.push_str(&format!(
"#[prost({}, tag=\"{}\")]\n",
ty_tag,
Expand Down Expand Up @@ -884,8 +873,6 @@ impl<'a> CodeGenerator<'a> {
}

fn resolve_type(&self, field: &FieldDescriptorProto, fq_message_name: &str) -> String {
let prost_path = self.config.prost_path.as_deref().unwrap_or("::prost");

match field.r#type() {
Type::Float => String::from("f32"),
Type::Double => String::from("f64"),
Expand All @@ -894,7 +881,14 @@ impl<'a> CodeGenerator<'a> {
Type::Int32 | Type::Sfixed32 | Type::Sint32 | Type::Enum => String::from("i32"),
Type::Int64 | Type::Sfixed64 | Type::Sint64 => String::from("i64"),
Type::Bool => String::from("bool"),
Type::String => format!("{}::alloc::string::String", prost_path),
Type::String => self
.config
.string_type
.get_first_field(fq_message_name, field.name())
.copied()
.unwrap_or_default()
.rust_type()
.to_owned(),
Type::Bytes => self
.config
.bytes_type
Expand Down Expand Up @@ -941,6 +935,42 @@ impl<'a> CodeGenerator<'a> {
.join("::")
}

/// Use this method instead of [`Self::field_type_tag()`] when you need `string="string"`
/// instead of just `string` as the tag indication in the `#[prost]` attribute.
///
/// This applies only to [`Type::String`] and [`Type::Bytes`], other types are not concerned.
fn field_type_tag_detailed(
&self,
fq_message_name: &str,
field: &FieldDescriptorProto,
) -> Cow<'static, str> {
match field.r#type() {
Type::String => {
let string_type = self
.config
.string_type
.get_first_field(fq_message_name, field.name())
.copied()
.unwrap_or_default();
Cow::Owned(format!("string={:?}", string_type.annotation()))
}
Type::Bytes => {
let bytes_type = self
.config
.bytes_type
.get_first_field(fq_message_name, field.name())
.copied()
.unwrap_or_default();
Cow::Owned(format!("bytes={:?}", bytes_type.annotation()))
}
_ => self.field_type_tag(field),
}
}

/// Use this method instead of [`Self::field_type_tag_detailed()`] when you need `string`
/// instead of `string="string"` as the tag indication in the `#[prost]` attribute.
///
/// This applies only to [`Type::String`] and [`Type::Bytes`], other types are not concerned.
fn field_type_tag(&self, field: &FieldDescriptorProto) -> Cow<'static, str> {
match field.r#type() {
Type::Float => Cow::Borrowed("float"),
Expand Down Expand Up @@ -1222,6 +1252,7 @@ impl BytesType {
match self {
BytesType::Vec => "vec",
BytesType::Bytes => "bytes",
BytesType::BoxedSlice => "boxed_slice",
}
}

Expand All @@ -1230,6 +1261,25 @@ impl BytesType {
match self {
BytesType::Vec => "::prost::alloc::vec::Vec<u8>",
BytesType::Bytes => "::prost::bytes::Bytes",
BytesType::BoxedSlice => "::prost::alloc::boxed::Box<[u8]>",
}
}
}

impl StringType {
/// The `prost-derive` annotation type corresponding to the string type.
fn annotation(&self) -> &'static str {
match self {
Self::String => "string",
Self::BoxedStr => "boxed_str",
}
}

/// The fully-qualified Rust type corresponding to the string type.
fn rust_type(&self) -> &'static str {
match self {
Self::String => "::prost::alloc::string::String",
Self::BoxedStr => "::prost::alloc::boxed::Box<str>",
}
}
}
Expand Down
Expand Up @@ -18,7 +18,7 @@ pub mod container {
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Foo {
#[prost(string, tag="1")]
#[prost(string="string", tag="1")]
pub foo: ::prost::alloc::string::String,
}
#[allow(clippy::derive_partial_eq_without_eq)]
Expand Down
Expand Up @@ -18,7 +18,7 @@ pub mod container {
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Foo {
#[prost(string, tag = "1")]
#[prost(string = "string", tag = "1")]
pub foo: ::prost::alloc::string::String,
}
#[allow(clippy::derive_partial_eq_without_eq)]
Expand Down
4 changes: 2 additions & 2 deletions prost-build/src/fixtures/helloworld/_expected_helloworld.rs
Expand Up @@ -2,14 +2,14 @@
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Message {
#[prost(string, tag="1")]
#[prost(string="string", tag="1")]
pub say: ::prost::alloc::string::String,
}
#[derive(derive_builder::Builder)]
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Response {
#[prost(string, tag="1")]
#[prost(string="string", tag="1")]
pub say: ::prost::alloc::string::String,
}
#[some_enum_attr(u8)]
Expand Down
Expand Up @@ -2,14 +2,14 @@
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Message {
#[prost(string, tag = "1")]
#[prost(string = "string", tag = "1")]
pub say: ::prost::alloc::string::String,
}
#[derive(derive_builder::Builder)]
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Response {
#[prost(string, tag = "1")]
#[prost(string = "string", tag = "1")]
pub say: ::prost::alloc::string::String,
}
#[some_enum_attr(u8)]
Expand Down