From f26d130740f5ae68eaf5a71de15d126d6dd7217a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bastian=20K=C3=B6cher?= Date: Mon, 7 Jul 2025 21:08:40 +0200 Subject: [PATCH] Fix clippy warnings in derive macro (#747) Replace unsafe casts with format\! macro in field name generation. The old code was casting usize to u8 which triggered clippy warnings. Add test case to prevent regression. --- derive/src/encode.rs | 17 ++--------------- tests/mod.rs | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+), 15 deletions(-) diff --git a/derive/src/encode.rs b/derive/src/encode.rs index bf49d85d..e267d15f 100644 --- a/derive/src/encode.rs +++ b/derive/src/encode.rs @@ -12,8 +12,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -use std::str::from_utf8; - use proc_macro2::{Ident, Span, TokenStream}; use syn::{punctuated::Punctuated, spanned::Spanned, token::Comma, Data, Error, Field, Fields}; @@ -344,9 +342,8 @@ fn impl_encode(data: &Data, type_name: &Ident, crate_path: &syn::Path) -> TokenS Fields::Unnamed(ref fields) => { let fields = &fields.unnamed; let field_name = |i, _: &Option| { - let data = stringify(i as u8); - let ident = from_utf8(&data).expect("We never go beyond ASCII"); - let ident = Ident::new(ident, Span::call_site()); + let ident = + Ident::new(&format!("__unnamed_field_{i}__"), Span::call_site()); quote!(#ident) }; @@ -445,13 +442,3 @@ pub fn quote(data: &Data, type_name: &Ident, crate_path: &syn::Path) -> TokenStr impl_encode(data, type_name, crate_path) } } - -pub fn stringify(id: u8) -> [u8; 2] { - const CHARS: &[u8] = b"abcdefghijklmnopqrstuvwxyz"; - let len = CHARS.len() as u8; - let symbol = |id: u8| CHARS[(id % len) as usize]; - let a = symbol(id); - let b = symbol(id / len); - - [a, b] -} diff --git a/tests/mod.rs b/tests/mod.rs index 3ec184ba..f9cef8bd 100644 --- a/tests/mod.rs +++ b/tests/mod.rs @@ -978,3 +978,22 @@ fn cow_str_decode_with_mem_tracking() { let decoded = Cow::<'static, str>::decode_with_mem_limit(&mut &encoded[..], 6).unwrap(); assert_eq!(data, decoded); } + +#[test] +fn issue_747_enum_with_group_id_compiles() { + // Test case for issue #747: Clippy errors with 'casting usize to u8 may truncate the value' + pub type GroupId = u32; + + #[derive(Debug, Clone, PartialEq, DeriveEncode, DeriveDecode, Default)] + pub enum PostVisibility { + #[default] + Public, + Supporter, + Group(GroupId), + } + + let visibility = PostVisibility::Group(123); + let encoded = visibility.encode(); + let decoded = PostVisibility::decode(&mut &encoded[..]).unwrap(); + assert_eq!(visibility, decoded); +}