ramp
ramp copied to clipboard
Allow more aggressive reusing of existing allocations
Currently there's several methods that do from-scratch internal allocations, such as divmod, pow and square. It would be nice if there was a way to use this functionality in a way that can reuse temporaries, e.g.
/// computes `a/b` setting `self` to the quotient and `rem` to the remainder
fn divmod_from(&mut self, rem: &mut Int, a: &Int, b: &Int);
/// sets `self` to `a**pow`
fn pow_from(&mut self, a: &Int, pow: u32)
etc.
This applies to functions like add too, since something like t = &a + &b has to allocate, but could be written as t.add_from(&a, &b), and multiplication is even worse: t = a * b is likely to allocate, but the temporary t may be large enough (e.g. if its a temporary being used for multiple multiplications in a loop), so t.mul_from(&a, &b) would be better. (Notably, one can avoid the allocations by doing something like t.clone_from(&a); t *= &b, but this pays the O(n) cost of a memcpy and so isn't so great.)
(The _from naming scheme is purely hypothetical, and just so I can write some examples here.)
Sounds good. I've got an idea for it. Basically a set of traits for the operations, similar to the regular ones or the augmented ones.
First though I'm gonna do some refactoring since there's starting to be a fair bit of duplicated code in the various implementations. Need to factor it out to some unsafe functions (unsafe because the destination can alias the inputs in most cases). I've done add and sub and it seems to work fine.