Skip to content

Commit

Permalink
add option to skip Default impl on struct
Browse files Browse the repository at this point in the history
  • Loading branch information
losman0s committed Jul 27, 2022
1 parent 8b04272 commit 3cdb734
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 4 deletions.
15 changes: 13 additions & 2 deletions crates/anchor-idl/src/program.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ pub struct GeneratorOptions {
pub zero_copy: Option<PathList>,
/// List of `repr(packed)` structs.
pub packed: Option<PathList>,
/// List of structs that should have `Default` impl skipped.
pub skip_default: Option<PathList>,
}

fn path_list_to_string(list: Option<&PathList>) -> HashSet<String> {
Expand All @@ -40,15 +42,23 @@ impl GeneratorOptions {

let zero_copy = path_list_to_string(self.zero_copy.as_ref());
let packed = path_list_to_string(self.packed.as_ref());
let skip_default = path_list_to_string(self.skip_default.as_ref());

let mut all_structs: HashSet<String> = HashSet::new();
for struct_item in [&zero_copy, &packed, &skip_default].into_iter().flatten() {
if !all_structs.contains(struct_item) {
all_structs.insert(struct_item.clone());
}
}

let mut struct_opts: BTreeMap<String, StructOpts> = BTreeMap::new();
let all_structs: HashSet<&String> = zero_copy.union(&packed).collect::<HashSet<_>>();
all_structs.into_iter().for_each(|name| {
all_structs.iter().for_each(|name| {
struct_opts.insert(
name.to_string(),
StructOpts {
zero_copy: zero_copy.contains(name),
packed: packed.contains(name),
skip_default: skip_default.contains(name),
},
);
});
Expand All @@ -61,6 +71,7 @@ impl GeneratorOptions {
pub struct StructOpts {
pub packed: bool,
pub zero_copy: bool,
pub skip_default: bool,
}

pub struct Generator {
Expand Down
2 changes: 1 addition & 1 deletion crates/anchor-idl/src/typedef.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ pub fn generate_struct(
let fields_rendered = generate_fields(fields);
let props = get_field_list_properties(defs, fields);

let derive_default = if props.can_derive_default {
let derive_default = if props.can_derive_default && !opts.skip_default {
quote! {
#[derive(Default)]
}
Expand Down
11 changes: 10 additions & 1 deletion examples/whirlpools/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
anchor_gen::generate_cpi_interface!(
idl_path = "idl.json",
zero_copy(TickArray, Tick),
packed(TickArray, Tick)
packed(TickArray, Tick),
skip_default(WhirlpoolBumps)
);

impl Default for state::TickArray {
Expand All @@ -23,4 +24,12 @@ impl Default for state::TickArray {
}
}

impl Default for WhirlpoolBumps {
fn default() -> Self {
Self {
whirlpool_bump: Default::default(),
}
}
}

declare_id!("whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc");

0 comments on commit 3cdb734

Please sign in to comment.