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

InstructionData::data allocates on every call #2732

Closed
cavemanloverboy opened this issue Dec 13, 2023 · 1 comment
Closed

InstructionData::data allocates on every call #2732

cavemanloverboy opened this issue Dec 13, 2023 · 1 comment
Labels

Comments

@cavemanloverboy
Copy link
Contributor

cavemanloverboy commented Dec 13, 2023

At present, both in the client side and cpi context, using anchor's InstructionData::data() allocates a new `Vec on each call.

For a use case such as

for _ in 0..ITERATIONS {
    // cpi or tx build using InstructionDataImplementor { ... }.data()
}

its simply not necessary.

I propose a new trait method InstructionData::write_to, which would allow developers to write to an existing allocation.

pub trait InstructionData: Discriminator + AnchorSerialize {
    fn data(&self) -> Vec<u8> {
        let mut d = Self::discriminator().to_vec();
        d.append(&mut self.try_to_vec().expect("Should always serialize"));
        d
    }
    /// Clears `vec` and writes instruction data to it
    ///
    /// We use a Vec<u8> here because of the additional flexibility of re-allocation (only if necessary),
    /// and because the data field in `Instruction` expects a `Vec<u8>`.
    fn write_to(&self, mut vec: &mut Vec<u8>) {
        // Clear vector
        vec.clear();

        // Write discriminator and then Self
        borsh::to_writer(&mut vec, &Self::DISCRIMINATOR)
            .expect("Discriminator is infallibly serializable");
        borsh::to_writer(vec, &self).expect("InstructionData should be infallibly serializable");
    }
}

Example usage

let mut instruction = Instruction { ... };
for _ in 0..ITERATIONS {
    // update ix program_id, accounts if needed

    // update instruction data
    InstructionDataImplementor { .. }.write_to(&mut instruction.data);

    // cpi or tx build
}
@acheroncrypto
Copy link
Collaborator

Resolved in #2733

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants