Skip to content

Commit 2ddf2e2

Browse files
authored
lang: Optimize enums with all unit variants and empty arrays with Lazy (solana-foundation#4237)
1 parent 3eedaad commit 2ddf2e2

File tree

2 files changed

+16
-4
lines changed

2 files changed

+16
-4
lines changed

lang/derive/serde/src/lazy.rs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use proc_macro2::Literal;
2-
use quote::{format_ident, quote};
2+
use quote::{format_ident, quote, ToTokens};
33
use syn::{spanned::Spanned, Fields, Item};
44

55
pub fn gen_lazy(input: proc_macro::TokenStream) -> syn::Result<proc_macro2::TokenStream> {
@@ -24,7 +24,10 @@ pub fn gen_lazy(input: proc_macro::TokenStream) -> syn::Result<proc_macro2::Toke
2424
.enumerate()
2525
.map(|(i, size)| (Literal::usize_unsuffixed(i), size))
2626
.map(|(i, size)| quote! { Some(#i) => { #size } });
27-
27+
let sized = enm
28+
.variants
29+
.iter()
30+
.all(|variant| matches!(variant.fields, Fields::Unit));
2831
(
2932
&enm.ident,
3033
&enm.generics,
@@ -34,7 +37,7 @@ pub fn gen_lazy(input: proc_macro::TokenStream) -> syn::Result<proc_macro2::Toke
3437
_ => unreachable!(),
3538
}
3639
},
37-
quote!(false),
40+
sized.to_token_stream(),
3841
)
3942
}
4043
Item::Union(_) => return Err(syn::Error::new(item.span(), "Unions are not supported")),

lang/src/lazy.rs

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ impl_sized!(f64);
6464
impl_sized!(Pubkey);
6565

6666
impl<T: Lazy, const N: usize> Lazy for [T; N] {
67-
const SIZED: bool = T::SIZED;
67+
const SIZED: bool = N == 0 || T::SIZED;
6868

6969
#[inline(always)]
7070
fn size_of(buf: &[u8]) -> usize {
@@ -196,6 +196,15 @@ mod tests {
196196
len!(MyEnum::Unnamed(1, 2))
197197
);
198198
assert!(!MyEnum::SIZED);
199+
200+
#[derive(AnchorSerialize, AnchorDeserialize)]
201+
enum UnitEnum {
202+
A,
203+
B,
204+
}
205+
assert_eq!(UnitEnum::size_of(&[0]), len!(UnitEnum::A));
206+
assert_eq!(UnitEnum::size_of(&[1]), len!(UnitEnum::B));
207+
assert!(UnitEnum::SIZED);
199208
}
200209

201210
#[test]

0 commit comments

Comments
 (0)