Skip to content

Commit

Permalink
feat!(derive): no get, set for scalar enum fields
Browse files Browse the repository at this point in the history
The OpenEnum wrapper provides convenience methods now, and with more
guard rails.
  • Loading branch information
mzabaluev committed Nov 12, 2024
1 parent c0b885c commit 0c28bd5
Showing 1 changed file with 5 additions and 42 deletions.
47 changes: 5 additions & 42 deletions prost-derive/src/field/scalar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -284,45 +284,7 @@ impl Field {
};

if let Ty::Enumeration(ref ty) = self.ty {
let set = Ident::new(&format!("set_{}", ident_str), Span::call_site());
let set_doc = format!("Sets `{}` to the provided enum value.", ident_str);
Some(match self.kind {
Kind::Plain(ref default) | Kind::Required(ref default) => {
let get_doc = format!(
"Returns the enum value of `{}`, \
or the default if the field is set to an invalid enum value.",
ident_str,
);
quote! {
#[doc=#get_doc]
pub fn #get(&self) -> #ty {
self.#ident.unwrap_or(#default)
}

#[doc=#set_doc]
pub fn #set(&mut self, value: #ty) {
self.#ident = value.into();
}
}
}
Kind::Optional(ref default) => {
let get_doc = format!(
"Returns the enum value of `{}`, \
or the default if the field is unset or set to an invalid enum value.",
ident_str,
);
quote! {
#[doc=#get_doc]
pub fn #get(&self) -> #ty {
self.#ident.and_then(|x| { x.known() }).unwrap_or(#default)
}

#[doc=#set_doc]
pub fn #set(&mut self, value: #ty) {
self.#ident = ::core::option::Option::Some(value.into());
}
}
}
match self.kind {
Kind::Repeated | Kind::Packed => {
let iter_doc = format!(
"Returns an iterator which yields the valid enum values contained in `{}`.",
Expand All @@ -331,7 +293,7 @@ impl Field {
let push = Ident::new(&format!("push_{}", ident_str), Span::call_site());
let push_doc = format!("Appends the provided enum value to `{}`.", ident_str);
let wrapped_ty = quote!(::prost::OpenEnum<#ty>);
quote! {
Some(quote! {
#[doc=#iter_doc]
pub fn #get(&self) -> ::core::iter::FilterMap<
::core::iter::Cloned<::core::slice::Iter<#wrapped_ty>>,
Expand All @@ -343,9 +305,10 @@ impl Field {
pub fn #push(&mut self, value: #ty) {
self.#ident.push(value.into());
}
}
})
}
})
_ => None,
}
} else if let Kind::Optional(ref default) = self.kind {
let ty = self.ty.rust_ref_type();

Expand Down

0 comments on commit 0c28bd5

Please sign in to comment.